Sub topic 3
Ambiguous and nonexistent times around DST
Assume you know basic Python, pandas Series and DataFrame operations, and datetime values. This chapter focuses on daylight saving time (DST), when clocks change by one hour.
Ambiguous and nonexistent local times
When clocks move backward, a local time occurs twice. When clocks move forward, some local times never occur.
- Ambiguous time:
2024-11-03 01:30in New York occurs twice. - Nonexistent time:
2024-03-10 02:30in New York does not occur.
tz_localize raises an error by default. Resolve these cases explicitly.
import numpy as np
import pandas as pd
zone = "America/New_York"
fall = pd.DatetimeIndex(["2024-11-03 01:30"])
print(fall.tz_localize(zone, ambiguous=np.array([True])))
print(fall.tz_localize(zone, ambiguous="NaT"))
spring = pd.DatetimeIndex(["2024-03-10 02:30"])
print(spring.tz_localize(zone, nonexistent="shift_forward"))ambiguous=True selects the first occurrence. Other choices include False, "NaT", or "raise". For nonexistent times, choices include "shift_forward", "shift_backward", "NaT", or a time offset.
Calendar days versus 24-hour steps
A calendar day means the same local clock time on the next date. A fixed 24-hour duration means exactly 86,400 elapsed seconds. They differ across DST.
import pandas as pd
zone = "America/New_York"
print(pd.date_range("2024-03-09", periods=3, freq="D", tz=zone))
print(pd.date_range("2024-03-09", periods=3, freq="24h", tz=zone))Use D for local calendar schedules. Use 24h for elapsed-time measurements.
Resampling and grouping by local day
Convert timestamps to the desired local zone before grouping or resampling. Otherwise, UTC midnight may split a local business day.
local = df.set_index("timestamp").tz_convert("America/New_York")
daily = local["sales"].resample("D").sum()
by_day = local.groupby(local.index.date)["sales"].sum()Removing time zones and saving data
Use tz_convert("UTC") before storage when the instant must be preserved consistently. Use tz_localize(None) only when you intentionally want to remove the zone information.
utc_values = local.index.tz_convert("UTC")
wall_clock = local.index.tz_localize(None)Time zone backends
Pandas accepts IANA names such as America/New_York. Python's zoneinfo is the modern standard backend. dateutil and pytz are also supported for compatibility, but avoid mixing backend objects in one workflow.
Exercise
Which operation changes an instant to another zone: tzlocalize or tzconvert?
Show answer
tzconvert changes the displayed zone while preserving the instant. tzlocalize attaches a zone to naive wall-clock values.