Sub topic 14
Time zones and daylight saving time
This chapter assumes you can already call resample() with a frequency string and an aggregation. It also assumes you know what a DatetimeIndex is. Here you will see how bins behave when the index carries a time zone, why some days are 23 or 25 hours long, and how to avoid the usual mistakes around daylight saving time (DST).
Naive and aware indexes
A naive index has no time zone. Its timestamps are just wall-clock readings, and pandas treats every day as exactly 24 hours.
A time-zone-aware index attaches a zone such as America/New_York or UTC to each timestamp. Each timestamp then maps to one exact instant. resample() uses the zone to decide where bins start and end.
This gives one rule to remember. Calendar-based bins ("D", "W", "MS") follow local wall-clock boundaries in the index's zone. Fixed-duration bins ("h", "15min", "24h") count elapsed time.
A day that has 23 hours
In the United States, clocks jump from 02:00 to 03:00 on 2024-03-10. That local day contains only 23 hours. The following code counts how many hourly rows land in each daily bin:
import pandas as pd
idx = pd.date_range(
"2024-03-09", "2024-03-11 23:00", freq="h", tz="America/New_York"
)
s = pd.Series(1, index=idx)
print(s.resample("D").sum())The output is:
2024-03-09 00:00:00-05:00 24
2024-03-10 00:00:00-05:00 23
2024-03-11 00:00:00-04:00 24
Freq: D, dtype: int64Each label is local midnight, and the UTC offset changes from -05:00 to -04:00 after the transition. The middle bin holds 23 rows because one local hour never happened.
This matters for aggregations. A daily sum() of an hourly quantity such as energy use covers 23 hours on this date. A daily mean() is unaffected by the missing hour, but a count() is not.
A day that has 25 hours
On 2024-11-03 the clocks fall back from 02:00 to 01:00, so 01:00 to 02:00 happens twice. That local day has 25 hours. The following code builds the index from UTC instants and converts it, which avoids any ambiguity:
import pandas as pd
idx = pd.date_range(
"2024-11-03 04:00", periods=30, freq="h", tz="UTC"
).tz_convert("America/New_York")
s = pd.Series(1, index=idx)
print(s.resample("D").sum())The output is:
2024-11-03 00:00:00-04:00 25
2024-11-04 00:00:00-05:00 5
Freq: D, dtype: int64Both occurrences of the 01:00 hour are kept as separate rows because they have different offsets. Nothing is merged or dropped.
Fixed-duration bins versus calendar bins
"D" means a calendar day in the local zone. "24h" means exactly 24 elapsed hours. On ordinary days they agree, but across a DST change they do not. The following code compares them:
import pandas as pd
idx = pd.date_range(
"2024-03-09", "2024-03-11 23:00", freq="h", tz="America/New_York"
)
s = pd.Series(1, index=idx)
print(s.resample("D").sum())
print(s.resample("24h").sum())Bins for "24h" start at local midnight of the first day. After the spring-forward change, the third bin starts at 2024-03-11 01:00:00-04:00, because 24 elapsed hours after 2024-03-10 00:00-05:00 is 01:00 local time. The labels no longer match local days.
Choose the frequency by what the question means:
- Use
"D"for questions about local days, such as daily sales for a store. - Use
"24h"when you need equal-length windows, such as rate calculations.
Localizing naive data
Data often arrives as naive timestamps that were recorded in some zone. You must attach the zone with tz_localize() before resampling if daily bins should follow local days. Use tz_convert() only to change an already-aware index to another zone.
| Method | Starts from | Effect |
|---|---|---|
| `tz_localize("America/New_York")` | Naive index | Attaches a zone, and keeps the wall-clock reading |
| `tz_convert("UTC")` | Aware index | Keeps the instant, and changes the displayed zone |
Calling tz_convert() on a naive index raises TypeError. Calling tz_localize() with a zone on an index that already has one raises TypeError too.
For a Series or DataFrame whose index is a DatetimeIndex, call the method on the object itself, as in s.tz_localize("UTC"). If the timestamps are in a column, call df["date"].dt.tz_localize(...) and then resample with on="date".
Ambiguous and nonexistent times
Wall-clock readings can fail to map to one instant:
- During fall back, a reading like 01:30 is ambiguous. It matches two instants.
- During spring forward, a reading like 02:30 is nonexistent. It matches none.
By default tz_localize() raises an error for both. The following code resolves the ambiguous case:
import pandas as pd
naive = pd.to_datetime(
[
"2024-11-03 00:30",
"2024-11-03 01:30",
"2024-11-03 01:30",
"2024-11-03 02:30",
]
)
s = pd.Series([1, 2, 3, 4], index=naive)
local = s.tz_localize("America/New_York", ambiguous="infer")
print(local.index.strftime("%H:%M %z"))With ambiguous="infer", pandas assumes the repeated reading appears twice in order. The first copy is daylight time (-0400) and the second is standard time (-0500). Without this argument, the same call raises AmbiguousTimeError.
These are the options:
| Argument | Values | Meaning |
|---|---|---|
| `ambiguous` | `"infer"` | Infer the order from repeated readings in a sorted index |
| `ambiguous` | `"NaT"` | Turn ambiguous readings into missing timestamps |
| `ambiguous` | boolean array | `True` means daylight time, one entry per row |
| `nonexistent` | `"shift_forward"` | Move a missing time to the first valid instant after the gap |
| `nonexistent` | `"shift_backward"` | Move it to the last valid instant before the gap |
| `nonexistent` | `"NaT"` | Turn it into a missing timestamp |
The "infer" setting only works when the repeated readings are present in the data. If a logger recorded only one 01:30, pass an explicit boolean array or choose "NaT" and handle the gaps.
Resampling in UTC
Many pipelines avoid DST problems by resampling in UTC and converting the result for display. UTC has no transitions, so every "D" bin holds exactly 24 hours. The following code does this:
import pandas as pd
idx = pd.date_range("2024-03-09", periods=72, freq="h", tz="UTC")
s = pd.Series(1, index=idx)
daily_utc = s.resample("D").sum()
print(daily_utc.tolist())
print(daily_utc.tz_convert("America/New_York").index[0])The first line prints [24, 24, 24]. The second prints 2024-03-08 19:00:00-05:00. Converting afterward only relabels the bins. Each one still covers a UTC day, not a New York day, so the labels no longer sit on local midnight. Use this approach only when your analysis is truly zone-independent.
Common mistakes
- Resampling naive data and calling it local. Naive bins always have 24 hours. Totals for DST days will be wrong if the data is really local time.
- Using
"24h"for daily reports. Labels drift away from midnight after a transition. - Assuming every day has 24 rows. After you resample hourly data to daily, a count of 23 or 25 is correct on transition days. Do not treat it as missing data.
- Localizing without handling duplicates.
AmbiguousTimeErrorandNonExistentTimeErrorsignal real ambiguity in the source data. Decide how to resolve it rather than dropping rows blindly. - Mixing offsets in one column. A column of strings with different offsets, such as
-04:00and-05:00, produces an object column in many pandas versions. Convert withpd.to_datetime(col, utc=True)first, then usetz_convert().
Check your understanding
Exercise
An hourly aware index in America/New_York covers all of 2024-11-03, the day clocks fall back. What count do you expect from s.resample("D").count() for that day, and why?
Show answer
25. The local day contains the 01:00 hour twice, once at offset -04:00 and once at -05:00, and resample("D") bins by local calendar day, so both rows land in the same bin.
Exercise
You have naive hourly timestamps recorded in local Berlin time, and you want daily totals per local day. What two steps must happen before resample("D")?
Show answer
Attach the zone with tzlocalize("Europe/Berlin"), passing ambiguous= and nonexistent= as needed for the DST hours, so the index is aware. Then call resample("D"). Calling tzconvert on the naive index would raise a TypeError, and skipping localization gives 24-hour bins.
Exercise
Why do resample("D") and resample("24h") produce different labels for data spanning a spring-forward date in an aware index?
Show answer
"D" is a calendar-day bin, so labels stay at local midnight and the transition day has 23 hours. "24h" is a fixed elapsed duration, so after the clock jump its bins start at 01:00 local time.