Sub topic 10
Resampling and grouping by local day
This chapter assumes you know how tz_localize and tz_convert work, and that you are comfortable with resample and groupby on a DatetimeIndex. Here you will see how time zones change the way data is bucketed into days.
Why the zone matters for daily buckets
A day boundary is midnight in some time zone. If your index is in UTC, resample("D") cuts at UTC midnight. For a business in New York, that cut falls at 7 or 8 pm local time. Daily totals then mix the evening of one local day with the morning of the next.
To get local days, convert the index to the local zone first. Then resample.
import pandas as pd
idx = pd.date_range("2024-03-09 05:00", periods=71, freq="h", tz="UTC")
s = pd.Series(1, index=idx)
print(s.resample("D").sum())
# UTC days: 19, 24, 24, 4
local = s.tz_convert("America/New_York")
print(local.resample("D").sum())
# local days: 24, 23, 24The series starts at midnight New York time on 9 March. The clocks spring forward on 10 March, so that local day has only 23 hours. The local result shows 23 observations for that day. The UTC result shows no such pattern.
What resample does with a tz-aware index
resample builds its bins in the zone of the index. With the "D" frequency, each bin runs from one local midnight to the next. The bin edges carry the correct offset: -05:00 before the change and -04:00 after it.
This is the same distinction as in the previous chapter on calendar days versus fixed durations:
"D"is a calendar day. A bin can contain 23, 24, or 25 hours."24h"is a fixed duration. Every bin is exactly 24 elapsed hours, so edges drift away from local midnight after a DST change.
For reporting by local day, use "D". Use "24h" only when you need equal-length windows, for example for a rolling-rate calculation.
Grouping by local day with groupby
Sometimes the timestamps are a column, not the index. Convert the column, then reduce it to a day label with .dt.normalize(). This sets the time to local midnight and keeps the zone.
import pandas as pd
idx = pd.date_range("2024-03-09 05:00", periods=71, freq="h", tz="UTC")
df = pd.DataFrame({"ts": idx, "value": 1})
df["local_day"] = df["ts"].dt.tz_convert("America/New_York").dt.normalize()
print(df.groupby("local_day")["value"].sum())
# 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 24You can also call df.resample("D", on="ts"). In that case the column must already be in the local zone, because the bins follow whatever zone the column has.
daily = (
df.assign(ts=df["ts"].dt.tz_convert("America/New_York"))
.resample("D", on="ts")["value"]
.sum()
)
print(daily)Common errors
- Resampling before converting. The code runs without error and gives UTC days. Nothing warns you, so check the bin edges by printing the index.
- Using
.dt.dateas the group key. It returns Pythondateobjects. This drops the zone and gives an object-dtype column. It is correct for grouping, but you lose the tz-aware index and the ability to reindex withdate_range. - Assuming 24 rows per day. On DST days a complete hourly day has 23 or 25 rows. A check such as
count() == 24flags valid days as incomplete. - Localizing naive data you already stored in UTC. If the column is naive but its values are UTC, use
tz_localize("UTC")first, thentz_convert. Localizing straight to the local zone shifts every value and can raise errors on DST edges.
Checking for short and long days
You can count rows per local day to find the DST days.
hours = local.resample("D").size()
print(hours[hours != 24])
# 2024-03-10 00:00:00-05:00 23Exercise
Your hourly readings are indexed in UTC, and you need daily totals for Europe/Berlin. Write the line that does this, and explain why resampling the UTC index directly gives the wrong answer.
Show answer
Use s.tz_convert("Europe/Berlin").resample("D").sum(). Resampling the UTC index cuts days at UTC midnight, which is 1 am or 2 am in Berlin depending on the season, so readings from two Berlin days are mixed into one bucket. Converting first makes the bin edges fall at Berlin midnight.