Bird
Raised Fist0
Pandasdata~20 mins

Timezone handling basics in Pandas - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Timezone Handling Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this timezone conversion code?

Consider the following code that creates a timezone-naive datetime and then localizes it to 'UTC'. What will be the output?

Pandas
import pandas as pd
naive_dt = pd.Timestamp('2024-01-01 12:00:00')
localized_dt = naive_dt.tz_localize('UTC')
print(localized_dt)
A2024-01-01 12:00:00+00:00
B2024-01-01 12:00:00
C2024-01-01 07:00:00-05:00
DError: Cannot localize already tz-aware datetime
Attempts:
2 left
💡 Hint

Think about what tz_localize does to a naive datetime.

❓ data_output
intermediate
2:00remaining
What is the result of converting timezone from UTC to US/Eastern?

Given a timezone-aware datetime in UTC, what will be the result after converting it to US/Eastern timezone?

Pandas
import pandas as pd
utc_dt = pd.Timestamp('2024-06-01 15:00:00', tz='UTC')
est_dt = utc_dt.tz_convert('US/Eastern')
print(est_dt)
A2024-06-01 10:00:00-05:00
B2024-06-01 15:00:00-04:00
C2024-06-01 11:00:00-04:00
D2024-06-01 15:00:00+00:00
Attempts:
2 left
💡 Hint

Remember that US/Eastern is 4 hours behind UTC during daylight saving time in June.

🔧 Debug
advanced
2:00remaining
Why does this code raise an error when localizing a timezone-aware datetime?

Examine the code below. Why does it raise an error?

Pandas
import pandas as pd
dt = pd.Timestamp('2024-01-01 12:00:00', tz='UTC')
dt_localized = dt.tz_localize('US/Eastern')
ABecause <code>tz_localize</code> cannot be used on timezone-aware datetimes
BBecause <code>tz_localize</code> requires a naive datetime with no timezone
CBecause the datetime string format is incorrect
DBecause 'US/Eastern' is not a valid timezone
Attempts:
2 left
💡 Hint

Check the difference between tz_localize and tz_convert.

❓ visualization
advanced
3:00remaining
Which plot correctly shows hourly data converted from UTC to Asia/Tokyo timezone?

You have hourly data timestamps in UTC. After converting to Asia/Tokyo timezone, which plot correctly shows the shifted time on the x-axis?

Pandas
import pandas as pd
import matplotlib.pyplot as plt
idx = pd.date_range('2024-01-01 00:00', periods=3, freq='H', tz='UTC')
data = [1, 2, 3]
df = pd.DataFrame({'value': data}, index=idx)
df_tokyo = df.tz_convert('Asia/Tokyo')
df_tokyo.plot()
plt.show()
APlot with x-axis labels: 2023-12-31 15:00, 16:00, 17:00
BPlot with x-axis labels: 2024-01-01 00:00, 01:00, 02:00
CPlot with x-axis labels: 2024-01-01 03:00, 04:00, 05:00
DPlot with x-axis labels: 2024-01-01 09:00, 10:00, 11:00
Attempts:
2 left
💡 Hint

Asia/Tokyo is UTC+9 hours. Check how the timestamps shift.

🚀 Application
expert
3:00remaining
How many unique timezone-aware timestamps are in this DataFrame after conversion?

Given a DataFrame with timestamps localized to UTC, then converted to Europe/London timezone, how many unique timestamps remain?

Pandas
import pandas as pd
idx = pd.to_datetime(['2024-03-31 00:30', '2024-03-31 01:30', '2024-03-31 02:30'])
idx_utc = idx.tz_localize('UTC')
idx_london = idx_utc.tz_convert('Europe/London')
df = pd.DataFrame({'value': [10, 20, 30]}, index=idx_london)
unique_count = df.index.nunique()
print(unique_count)
A1
B3
C2
DRaises an error due to ambiguous times
Attempts:
2 left
💡 Hint

Consider daylight saving time change on 2024-03-31 in Europe/London.

Practice

(1/5)
1. What does the tz_localize method do in pandas when working with timestamps?
easy
A. Converts timestamps from one timezone to another.
B. Adds timezone information to timestamps without any timezone (naive timestamps).
C. Removes timezone information from timestamps.
D. Changes the timestamp format to string.

Solution

  1. Step 1: Understand naive timestamps

    Naive timestamps have no timezone information attached.
  2. Step 2: Role of tz_localize

    This method adds timezone info to naive timestamps without changing the actual time.
  3. Final Answer:

    Adds timezone information to timestamps without any timezone (naive timestamps). -> Option B
  4. Quick Check:

    tz_localize adds timezone [OK]
Hint: Remember: localize adds timezone, convert changes it [OK]
Common Mistakes:
  • Confusing tz_localize with tz_convert
  • Thinking tz_localize changes the time value
  • Assuming tz_localize removes timezone info
2. Which of the following is the correct way to convert a timezone-aware pandas datetime Series dt from UTC to US/Eastern timezone?
easy
A. dt.tz_convert('US/Eastern')
B. dt.tz_localize('UTC').tz_convert('US/Eastern')
C. dt.tz_localize('US/Eastern')
D. dt.tz_convert('UTC')

Solution

  1. Step 1: Check if dt is timezone-aware

    Since dt is timezone-aware, we use tz_convert to change its timezone.
  2. Step 2: Apply correct method

    tz_convert('US/Eastern') converts from current timezone (UTC) to US/Eastern.
  3. Final Answer:

    dt.tz_convert('US/Eastern') -> Option A
  4. Quick Check:

    Convert aware timestamps with tz_convert [OK]
Hint: Use tz_convert only on timezone-aware timestamps [OK]
Common Mistakes:
  • Using tz_localize on already aware timestamps
  • Not converting timezone properly
  • Confusing order of localization and conversion
3. Given the following code, what will be the output?
import pandas as pd
rng = pd.date_range('2024-01-01 12:00', periods=2, freq='H')
rng_utc = rng.tz_localize('UTC')
rng_est = rng_utc.tz_convert('US/Eastern')
print(rng_est)
medium
A. DatetimeIndex with times 17:00 and 18:00 in US/Eastern timezone
B. DatetimeIndex with times 12:00 and 13:00 in US/Eastern timezone
C. DatetimeIndex with times 07:00 and 08:00 in US/Eastern timezone
D. Error because tz_convert cannot be used after tz_localize

Solution

  1. Step 1: Localize naive timestamps to UTC

    The original times are 12:00 and 13:00 UTC after tz_localize('UTC').
  2. Step 2: Convert UTC times to US/Eastern timezone

    US/Eastern is UTC-5 in winter, so times become 07:00 and 08:00 with timezone info.
  3. Final Answer:

    DatetimeIndex with times 07:00 and 08:00 in US/Eastern timezone -> Option C
  4. Quick Check:

    UTC 12:00 -> EST 07:00 [OK]
Hint: Convert UTC to EST subtracts 5 hours [OK]
Common Mistakes:
  • Assuming times stay the same after conversion
  • Mixing up tz_localize and tz_convert order
  • Expecting error instead of valid output
4. What is wrong with this code snippet?
import pandas as pd
dt = pd.to_datetime(['2024-01-01 10:00', '2024-01-01 11:00'])
dt = dt.tz_convert('Europe/London')
medium
A. Cannot use tz_convert on naive timestamps; must localize first.
B. The timezone string 'Europe/London' is invalid.
C. The to_datetime function needs a timezone argument.
D. The code is correct and runs without error.

Solution

  1. Step 1: Check timestamp awareness

    The timestamps created by to_datetime are naive (no timezone).
  2. Step 2: Understand tz_convert usage

    tz_convert requires timestamps to be timezone-aware; naive timestamps must use tz_localize first.
  3. Final Answer:

    Cannot use tz_convert on naive timestamps; must localize first. -> Option A
  4. Quick Check:

    tz_convert needs aware timestamps [OK]
Hint: Localize before convert on naive timestamps [OK]
Common Mistakes:
  • Trying to convert timezone without localizing
  • Assuming to_datetime adds timezone automatically
  • Confusing error cause with invalid timezone string
5. You have a pandas Series of timestamps without timezone info representing local times in New York. You want to convert them to UTC timestamps correctly considering daylight saving time. Which sequence of operations should you perform?
hard
A. Convert timestamps to string first, then parse with UTC timezone.
B. Use tz_convert('UTC') directly on naive timestamps.
C. Use tz_localize('UTC') then tz_convert('America/New_York').
D. Use tz_localize('America/New_York') then tz_convert('UTC').

Solution

  1. Step 1: Localize naive timestamps to New York timezone

    Since timestamps are local New York times without timezone, use tz_localize('America/New_York') to mark them as such, correctly handling daylight saving.
  2. Step 2: Convert localized timestamps to UTC

    Use tz_convert('UTC') to get equivalent UTC times.
  3. Final Answer:

    Use tz_localize('America/New_York') then tz_convert('UTC'). -> Option D
  4. Quick Check:

    Localize then convert for correct timezone shifts [OK]
Hint: Localize first, then convert to UTC [OK]
Common Mistakes:
  • Converting naive timestamps directly
  • Localizing to wrong timezone first
  • Ignoring daylight saving time effects
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard