Sub topic 10
Resampling and grouping by local day
This chapter assumes you know how to use tz_localize and tz_convert, and you have a working model of tz-aware dtypes. It also assumes you are comfortable with resample and groupby on a naive DatetimeIndex. The earlier chapters covered those. Here you will combine them: aggregate data by the day your business or users experience, not by the UTC day.
Why the day boundary depends on the zone
A "day" is a window between two midnights, and midnight happens at a different instant in each zone. An event at 22:00 on January 1 in New York is at 03:00 on January 2 in UTC. If you aggregate by UTC day, you put that event in the wrong day for anyone who thinks in New York time.
The rule to remember is that pandas builds the bins in the zone the data currently carries. It does not choose a zone for you. A UTC index gives UTC days. A New York index gives New York days. So you must call tz_convert before you aggregate.
import pandas as pd
utc_times = pd.to_datetime(
["2024-01-02 03:00", "2024-01-02 04:00", "2024-01-02 06:00"], utc=True
)
sales = pd.Series([10, 20, 30], index=utc_times)
print(sales.resample("D").sum())
# 2024-01-02 00:00:00+00:00 60
local = sales.tz_convert("America/New_York")
print(local.resample("D").sum())
# 2024-01-01 00:00:00-05:00 30
# 2024-01-02 00:00:00-05:00 30The three events are the same instants in both calls. In New York they happened at 22:00 and 23:00 on January 1, and at 01:00 on January 2. Only the labels and the bin edges changed.
Resampling a tz-aware index
resample needs a DatetimeIndex (or the on= argument for a column). With a tz-aware index, the "D" bin edges fall on local midnight. The offset in the label changes when the clocks change.
Here is hourly data across the March 2024 spring-forward in New York. On March 10 the clock jumps from 02:00 to 03:00, so that local day is 23 hours long.
import pandas as pd
idx = pd.date_range("2024-03-09", periods=71, freq="h", tz="America/New_York")
hourly = pd.Series(1, index=idx)
print(hourly.resample("D").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 24The 71 hourly values cover exactly three local days: 24, 23 and 24 hours. The labels are all local midnight, but the offset moves from -05:00 to -04:00 on March 11. The bin for March 10 holds only 23 observations because only 23 hours existed.
The reverse happens in autumn. On November 3, 2024 the clocks fall back, so that day has 25 hours. A bin that counts hourly rows reports 25 for that day.
Sums and counts on short or long days
A 23-hour or 25-hour day can distort your numbers. If you sum an hourly metric, the DST days look lower or higher than their neighbours for a reason unrelated to your business. Which aggregation you pick matters:
| Aggregation | Effect on a 23-hour day | Effect on a 25-hour day |
|---|---|---|
| `sum` of an hourly quantity | Total is smaller because one hour is missing | Total is larger because one hour is repeated |
| `mean` of an hourly quantity | Unaffected by the day length | Unaffected by the day length |
| `size` or `count` | 23 | 25 |
| `max`, `min` | Unaffected unless the lost hour held the extreme | Unaffected |
If you compare days, either use a rate (a mean per hour) or accept that the sum on those two days per year is a true total for a shorter or longer day. Decide on purpose, and say which one in your report.
Grouping a column by local day
Often the timestamps live in a column, not the index. You have three common options.
import pandas as pd
df = pd.DataFrame(
{
"ts": pd.to_datetime(
["2024-01-02 03:00", "2024-01-02 04:00", "2024-01-02 06:00"], utc=True
),
"amount": [10, 20, 30],
}
)
df["local_ts"] = df["ts"].dt.tz_convert("America/New_York")
by_date = df.groupby(df["local_ts"].dt.date)["amount"].sum()
by_norm = df.groupby(df["local_ts"].dt.normalize())["amount"].sum()
by_grouper = df.groupby(pd.Grouper(key="local_ts", freq="D"))["amount"].sum()
print(by_date) # index: datetime.date(2024, 1, 1), datetime.date(2024, 1, 2)
print(by_norm) # index: tz-aware local midnights
print(by_grouper) # same as by_norm, plus empty days if anyAll three give the same totals here (30 and 30). They differ in what the result index looks like and how they treat missing days.
| Method | Key type | Keeps the zone | Includes empty days |
|---|---|---|---|
| `dt.date` | Python `date` objects | No | No |
| `dt.normalize()` | tz-aware midnight timestamps | Yes | No |
| `pd.Grouper(key=..., freq="D")` | tz-aware midnight timestamps | Yes | Yes |
Choose Grouper when you want a continuous daily series, for example before plotting or joining to another daily table. Choose dt.date when you want plain dates as keys and do not need the zone in the result. The trade-off with dt.date is that you cannot later reindex against a tz-aware daily range without converting the keys back.
Empty days
resample creates a bin for every day between the first and last timestamp, including days with no rows. sum then returns 0 for those days, and mean returns NaN. A plain groupby skips days without data. This difference often explains why two reports disagree about the number of rows.
import pandas as pd
idx = pd.DatetimeIndex(
["2024-03-01 10:00", "2024-03-04 10:00"], tz="America/New_York"
)
s = pd.Series([1, 2], index=idx)
print(s.resample("D").sum()) # 4 rows: Mar 1, 2, 3, 4 (Mar 2 and 3 are 0)
print(s.groupby(s.index.date).sum()) # 2 rows: Mar 1 and Mar 4Other calendar frequencies
Weekly and monthly bins also follow local calendar boundaries. With "W", weeks end on a local Sunday midnight by default. A monthly bin starts at local midnight on the first day of the month, so a timestamp at 23:30 on January 31 in New York falls in January even though it is already February in UTC.
import pandas as pd
ts = pd.DatetimeIndex(["2024-02-01 03:00"], tz="UTC")
s = pd.Series([1], index=ts)
print(s.resample("MS").sum())
# 2024-02-01 00:00:00+00:00 1
print(s.tz_convert("America/New_York").resample("MS").sum())
# 2024-01-01 00:00:00-05:00 1The same instant lands in February when binned in UTC and in January when binned in New York. Month-end reports are where this causes the most visible mistakes, because totals shift between months.
The monthly start alias "MS" works in all recent pandas versions. For month-end bins, newer versions use "ME" and warn about the old "M".
Fixed-length bins versus calendar bins
The previous chapter showed that "D" and "24h" behave differently in date_range. The same distinction applies to resampling. A "D" bin is a local calendar day. A bin like "24h" has a fixed length of 24 elapsed hours, so after a DST change its edges no longer line up with local midnight.
Use "D" for any report that people read as "per day". Use fixed lengths such as "1h", "15min" or "6h" when you really mean elapsed time, for example sensor data where every bin must hold the same duration.
Sub-day frequencies are safe across DST because they work on absolute time. On the fall-back day the repeated hour appears as two separate hourly bins, one for each occurrence. Both carry the same wall-clock hour but different offsets (-04:00 and -05:00), so they never merge.
Common errors
- Resampling before converting. The data is in UTC, you call
resample("D"), and every daily total is for the UTC day. Convert first. - Localizing during aggregation. If your index is naive local time, call
tz_localizeonce before you aggregate. If the data crosses a fall-back hour, passambiguous=as covered earlier, or localization will raiseAmbiguousTimeError. - Mixed offsets in a column. Strings with different offsets parse to an
objectcolumn unless you passutc=True. The.dtaccessor andGrouperdo not work on that column. Parse withutc=True, thentz_convert. - Using
dt.dateand expecting a time zone. The keys are plain dates with no zone attached. This is fine for display and wrong if you later merge them with tz-aware data. - Reading DST-day totals as a trend. A 23-hour day has less data. Normalize by hours observed (
size) or use a mean. - Choosing the wrong zone. Group by the zone that defines the business day, such as the store's zone or the company's reporting zone. Do not use the analyst's laptop zone.
A complete pattern
This function turns raw UTC events into a daily table for a given zone. It also records how many hours each local day contained, which lets you spot DST days.
import pandas as pd
def daily_report(df, ts_col, value_col, zone):
local = df.set_index(df[ts_col].dt.tz_convert(zone))
daily = local[value_col].resample("D").agg(["sum", "mean", "size"])
daily.index.name = "local_day"
return daily
events = pd.DataFrame(
{
"ts": pd.date_range("2024-03-09 05:00", periods=71, freq="h", tz="UTC"),
"value": 1.0,
}
)
report = daily_report(events, "ts", "value", "America/New_York")
print(report)Here the UTC series starts at 05:00 UTC, which is local midnight (00:00 EST) on March 9. The first row counts the 24 hours of March 9, and the second row counts the 23 hours of March 10, because both are bins of local days. The size column reveals the short day.
Summary
- Convert to the reporting zone with
tz_convertbefore you resample or group. resample("D")on a tz-aware index bins by local calendar days. The offset in the labels changes with DST.- On a DST day the bin holds 23 or 25 hours, so sums change but means do not.
pd.Grouper(freq="D")keeps the zone and fills empty days.dt.datedrops the zone and skips them.- Weekly and monthly bins also use local boundaries, so the same instant can land in different months in different zones.
- Use sub-day frequencies for elapsed time and
"D"for calendar days.
Exercise
Hourly data is stored in UTC and covers November 3, 2024, the day clocks fall back in New York. You run s.tz_convert("America/New_York").resample("D").size(). How many rows does the bin for November 3 report, and why?
Show answer
It reports 25. The local day of November 3 has 25 elapsed hours because the 01:00 hour happens twice. Hourly data stored in UTC has one row per elapsed hour, so the local-day bin contains 25 rows.
Exercise
A DataFrame has a tz-aware UTC column ts and a numeric column amount. Write one expression that gives the total amount per Los Angeles calendar day, including days with no events.
Show answer
df.groupby(pd.Grouper(key="ts", freq="D"))["amount"].sum() would group by UTC days, so convert first. For example: df["la"] = df["ts"].dt.tzconvert("America/LosAngeles") and then df.groupby(pd.Grouper(key="la", freq="D"))["amount"].sum(). Grouper with freq="D" creates bins for empty days, and they sum to 0.
Exercise
Why can summing an hourly metric per local day make March 10, 2024 look lower than the days around it in New York, and what two options do you have?
Show answer
March 10 has only 23 hours because the clock skips 02:00 to 03:00, so a sum covers one hour less. You can either report a per-hour rate such as the mean, or keep the sum and note that the day is shorter, optionally including a size column that shows the 23 observed hours.