Time series in pandas: dates, resampling and rolling windows, and a year over year figure you can trust

TL;DR

Difficulty: Intermediate

Every time series number rests on three decisions: the clock, the calendar and the comparison.

  • Clock: parse timestamps with their zone, store in UTC, convert once to the shop's local time before forming days.
  • Calendar: resample with the current aliases (ME, QE, YE, h), use sum(min_count=1) so a lost day is a gap and not a zero, keep partial periods out of charts.
  • Comparison: 28 day rolling averages with an explicit minimum, year over year matched to the same weekday 52 weeks earlier, and moving events such as Black Friday compared event against event.

November flat, December up 17%, February up 15%: the business did not change, the calendar did. This chapter builds an example shop's daily revenue from a UTC order export, resamples it to weeks and months, smooths it with rolling windows, and computes year over year growth that survives leap years, lost export days and a Black Friday that moves.

Three decisions before any time series chart

Almost every number a shop reports has a date on it. Revenue yesterday, orders this week, growth on last year, the 28 day average on the dashboard. And almost every argument about those numbers is really an argument about dates that nobody had: "the export says 1,912 orders on Tuesday, GA4 says 1,870", "November was flat, how can the year be up 8%?", "why does the September figure look like a crash?".

Here is the idea I want you to take from this chapter, before a single line of code. Every time series number rests on three decisions, and the trouble starts when nobody made them on purpose:

  1. The clock. Which time zone decides what "a day" is? The shop export, GA4 and the ad platforms each answer differently.
  2. The calendar. Which days belong together? A week from Monday to Sunday, an ISO week, a calendar month, a month with one day missing, a month that is not over yet.
  3. The comparison. What is "last year"? The same date, the same weekday, or the same event?

pandas gives you a tool for each decision: time zone conversion for the clock, resample and periods for the calendar, shift and rolling windows for the comparison. The tools are easy. Making the three decisions explicitly, and writing them next to the chart, is the part that saves the meeting.

Tap or click to enlarge

This is chapter nine of the series. It builds on group by and pivot tables in pandas, because resampling is a group by on time, and on cleaning data in pandas, because a date column is only useful once it really is a date. The concepts follow McKinney's chapter on time series1 and the pandas user guide2, with the API as it stands in September 2025.

For the person who commissions this

If you only read one section, read this one. You do not need the code to judge a time series report. You need four questions, and you can ask them in any meeting:

  • "Which time zone is a day in?" The answer should be the shop's own local time, for every source, written down. If the shop export is in UTC and GA4 in UK time, the two will disagree on summer evenings, and both are "right".
  • "Is the last period complete?" A month that ends on the 21st is not a bad month. It is a short one. A chart that shows it next to full months without a label is misleading by accident.
  • "Is a missing day a zero?" A day with no data because an export failed is not a day with no sales. pandas will happily turn the first into the second unless someone tells it not to.
  • "Last year compared how?" Same date, same weekday, or same event? For Black Friday, Easter and leap years the answers differ by several points of growth.

If the analyst can answer all four in one sentence each, the numbers are probably sound. If not, ask for them to be added under the chart. The data storytelling chapter on showing time covers how to present the result once it is right.

The example shop and its data

The worked examples use an invented shop. Fernhill Home in York sells candles, ceramics and textiles online (fernhillhome.example). Grace founded it, Tariq is the analyst. It has about 1,200 products, takes about 48,000 orders a year from about 21,000 customers at an average order value of £58, and runs Google Ads, Meta ads and a newsletter. Tariq's standing question is "which channel really pays back, and what should we do with next month's budget?". Before he can answer any of that, he needs a daily revenue series he trusts.

The shop's order export gives every order with a timestamp in UTC (Coordinated Universal Time, the time zone with no daylight saving), which is how most shop systems store time. It is the trap of this chapter: UTC is right for storing, wrong for reporting.

Example: generating the shop's orders

Every code block in this chapter runs in order in one notebook. If you have not set one up yet, the first chapter of this series walks through it. I used Python 3.13 with pandas 2.3.2, NumPy 2.3.3 and holidays 0.81, the versions current in September 2025.

The first block builds the data: daily demand with a trend of about 7% a year, a quiet summer and a busy winter, a weekday pattern, Black Friday and Cyber Monday in 2023 and 2024, and the Christmas dip. Then it turns daily demand into single orders with a local time of day and a value, and writes the timestamp out as UTC text, the way the export would. One day of the export is lost on purpose, because that happens.

import numpy as np
import pandas as pd

rng = np.random.default_rng(2025)
TZ = "Europe/London"          # the shop's local time zone
AOV = 58.0                    # average order value in pounds

days = pd.date_range("2023-01-01", "2025-09-21", freq="D")
n = len(days)

trend = 1.07 ** (np.arange(n) / 365.25 - 1.5)             # about 7% growth a year
month_mult = np.array([0.84, 0.80, 0.90, 0.92, 0.94, 0.88,
                       0.84, 0.86, 0.96, 1.06, 1.22, 1.30])
season = (month_mult / month_mult.mean())[days.month - 1]  # quiet summer, busy winter
wd_mult = np.array([1.10, 1.06, 1.02, 0.99, 0.93, 0.86, 1.04])  # Monday to Sunday
weekday = (wd_mult / wd_mult.mean())[days.dayofweek]

events = pd.Series(1.0, index=days)
for bf in pd.to_datetime(["2023-11-24", "2024-11-29"]):    # Black Friday
    events[bf - pd.Timedelta(days=7):bf - pd.Timedelta(days=1)] *= 1.25
    events[bf] *= 3.2
    events[bf + pd.Timedelta(days=1)] *= 1.9
    events[bf + pd.Timedelta(days=2)] *= 1.8
    events[bf + pd.Timedelta(days=3)] *= 2.6                 # Cyber Monday
for y in [2023, 2024]:                                       # Christmas
    events[f"{y}-12-19":f"{y}-12-23"] *= 0.70
    events[f"{y}-12-24"] *= 0.40
    events[f"{y}-12-25"] *= 0.30
    events[f"{y}-12-26"] *= 1.60
    events[f"{y}-12-27":f"{y}-12-31"] *= 1.20

orders_per_day = rng.poisson(131.5 * trend * season * weekday * events.to_numpy())

# Each order gets a local time of day (lunch and evening peaks) and a value
hour_w = np.array([2, 1, 1, 1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 6, 7, 8, 9, 10, 9, 6, 4])
local_day = np.repeat(days.to_numpy(), orders_per_day)
hours = rng.choice(24, size=local_day.size, p=hour_w / hour_w.sum())
secs = rng.integers(0, 3600, size=local_day.size)
local = (pd.DatetimeIndex(local_day)
         + pd.to_timedelta(hours, unit="h")
         + pd.to_timedelta(secs, unit="s")
        ).tz_localize(TZ, ambiguous=False, nonexistent="shift_forward")

orders = pd.DataFrame({
    "order_id": np.arange(100001, 100001 + local_day.size),
    "created_at": local.tz_convert("UTC").strftime("%Y-%m-%dT%H:%M:%SZ"),  # UTC text, like the export
    "revenue": rng.gamma(shape=4.0, scale=AOV / 4, size=local_day.size).round(2),
})
# The export lost one whole day: 12 March 2024 (local time)
orders = orders[local.normalize() != pd.Timestamp("2024-03-12", tz=TZ)].reset_index(drop=True)
print(orders.head(3))
print(len(orders), round(orders["revenue"].sum()))
#    order_id            created_at  revenue
# 0    100001  2023-01-01T19:33:52Z    38.48
# 1    100002  2023-01-01T15:21:33Z    39.69
# 2    100003  2023-01-01T20:03:28Z    67.36
# 129280 7498108

That is 129,280 orders and £7.5 million of revenue from 1 January 2023 to Sunday 21 September 2025, roughly 48,000 orders a year. Three things in the block are worth a second look. pd.date_range builds a run of dates at a fixed frequency, here "D" for daily. tz_localize tells pandas which time zone a naive time (one without a zone) belongs to. And the two arguments ambiguous and nonexistent handle the two awkward hours a year: the hour that happens twice when the clocks go back in October, and the hour that never happens when they go forward in March. You will see those again.

The clock: store in UTC, report in local time

A timestamp is a point in time. A date is a label that depends on where you stand. In summer, UK time is one hour ahead of UTC. An order placed at 12.30am in York on 15 July is stamped 11.30pm on 14 July in UTC. Same order, two dates. That one hour after midnight is where the trouble lives.

pandas stores every time zone aware timestamp internally in UTC and only shows its fields (day, hour, minute) in the zone you attach2. That is the right design, and it gives you the rule: store and join in UTC, convert to the shop's local time once, at the moment you turn timestamps into days.

Each source has its own clock, and you need to know which:

SourceWhat the timestamp isWhat "a day" is
Shop order exportUsually UTC, check the column header or a known orderWhatever you decide
GA4 export in BigQueryevent_timestamp in microseconds, UTCevent_date in the property's time zone3
Google Ads reportNo timestamps, only daysThe account time zone, fixed when the account was set up4
Meta Ads reportNo timestamps, only daysThe ad account's time zone, check it in the account settings
Newsletter toolSend time, often in the user's display zoneCheck the export settings

GA4 is the interesting one. Its BigQuery export carries both: event_date as a string in the property's time zone and event_timestamp in UTC microseconds3. If Fernhill Home's GA4 property is set to Europe/London, event_date already matches the shop's local day. If someone set the property up in another zone years ago, it will not, and every daily comparison with the shop export will be off by a few hours of orders. The BigQuery setup article shows where those tables come from, and the chapter on loading business data shows how to flatten them in pandas.

Example: converting the order export to York time

Tariq parses the text column as UTC first, then converts. utc=True tells pd.to_datetime that the text means UTC, and .dt.tz_convert moves the same instant into another zone.

orders["created_at"] = pd.to_datetime(orders["created_at"], utc=True)
orders["created_local"] = orders["created_at"].dt.tz_convert(TZ)
print(orders[["created_at", "created_local"]].iloc[[0, -1]])
print(orders["created_local"].dtype)
#                       created_at             created_local
# 0      2023-01-01 19:33:52+00:00 2023-01-01 19:33:52+00:00
# 129279 2025-09-21 04:33:27+00:00 2025-09-21 05:33:27+01:00
# datetime64[ns, Europe/London]

In January the two columns are identical, because UK winter time equals UTC. In September they differ by an hour, shown as +01:00. Same instant, two labels.

Now the question that matters: how many orders land on a different date depending on which clock you use?

moved = orders["created_at"].dt.date != orders["created_local"].dt.date
print(moved.sum(), f"{moved.mean():.1%}")
print(orders.loc[moved, "created_local"].dt.month.value_counts().sort_index().to_dict())
# 1271 1.0%
# {3: 13, 4: 203, 5: 179, 6: 202, 7: 183, 8: 181, 9: 182, 10: 128}

day_utc = orders.groupby(orders["created_at"].dt.date)["revenue"].sum()
day_local = orders.groupby(orders["created_local"].dt.date)["revenue"].sum()
diff = (day_local - day_utc).abs()
print(round(diff.max()), diff.idxmax())
# 485 2023-09-24

1,271 orders, 1.0% of the total, change date. All of them fall between late March and late October, the months of British Summer Time, and all of them are orders placed between midnight and 1am local time. On the worst day, the daily total differs by £485. Small on a year, large enough to make Tuesday's figure disagree with GA4, and much larger for a shop whose customers shop late or whose local zone sits further from UTC (a German or Austrian shop is one or two hours ahead, so the gap is there all year).

The two strange days a year

On the last Sunday in March a UK day has 23 hours, and on the last Sunday in October it has 25. If you resample a time zone aware series to days, pandas uses real local days, so those two days are a little lighter and a little heavier in hours. That is correct. If you instead built days by hand from UTC hours, you would quietly shift an hour of orders across midnight twice a year. Let pandas do it with the zone attached.

The calendar: from orders to a daily series

resample is a group by on time. You give it a frequency, it puts every row into a time bin, and you choose how to summarise each bin. It works on a Series or DataFrame whose index is a DatetimeIndex (or with on= for a column).

Example: daily revenue, and the zero that is really a gap

s = orders.set_index("created_local")["revenue"].sort_index()
daily_zero = s.resample("D").sum()
daily = s.resample("D").sum(min_count=1)
print(daily_zero["2024-03-11":"2024-03-13"].round(0).to_dict())
print(daily[daily.isna()].index.date)
# {... 2024-03-11: 8054.0, 2024-03-12: 0.0, 2024-03-13: 6494.0}
# [datetime.date(2024, 3, 12)]

This is the most common silent error in time series work. The sum of an empty bin is 0 by default, so daily_zero reports that Fernhill Home sold nothing on Tuesday 12 March 2024. It did sell, about £8,000 worth. The export lost the day. With min_count=1, pandas says "a sum needs at least one value", and the empty day becomes NaN (not a number, pandas' marker for missing), which is the truth: nobody knows.

Why does it matter? Because every later step treats a zero as a real day. A 28 day average drops by about £290, a monthly total drops by £8,000, and March 2024 suddenly looks like a weak month. Later in this chapter you will see that error flow all the way into a year over year figure.

My rule of thumb: a zero needs a reason. For a shop of this size a day with no orders is impossible, so an empty day is always a gap. For a small B2B shop a zero can be real. Decide which, per series, and write it down.

Then Tariq drops the time zone. Once every timestamp has been put into its local day, the zone has done its job, and plain dates are easier to join with Google Ads and Meta reports, which also deliver plain local dates.

daily = daily.tz_localize(None)        # local calendar dates from here on
daily.index.name = "date"
print(daily.index.min().date(), daily.index.max().date(), len(daily))
# 2023-01-01 2025-09-21 995

full = pd.date_range(daily.index.min(), daily.index.max(), freq="D")
print(len(full) - daily.notna().sum())   # days without data
print(daily.index.equals(full))          # is every calendar day present as a row?
# 1
# True

The second check is worth keeping in every notebook. Resampling already created a row for every calendar day, and exactly one of them is empty. If you load a daily report that was never resampled (a Google Ads export, say), days with no spend are often simply missing rows. reindex(full) adds them back, and then you decide, again, whether each missing value is a zero or a gap.

Weeks and months: resample rules and their labels

Downsampling means going from a finer frequency to a coarser one: days to weeks, weeks to months. You need a rule (the frequency alias) and you need to know how the result is labelled. The labels are where people trip.

RuleBinLabel on the resultTypical use
"D"Calendar dayThe dayDaily reporting
"W" or "W-SUN"Monday to SundayThe Sunday that ends the weekUK and European trading weeks
"W-SAT"Sunday to SaturdayThe SaturdayUS style weeks
"MS"Calendar monthThe 1st of the monthMonthly reports, easy to read
"ME"Calendar monthThe last day of the monthFinance style month end
"QE", "QS"Calendar quarterQuarter end, quarter startBoard packs
"YE", "YS"Calendar yearYear end, year startAnnual totals
"h"HourThe start of the hourIntraday patterns, campaign timing

Two notes. First, pandas 2.2 renamed several aliases: month end is now "ME" instead of "M", quarter end "QE", year end "YE", business month end "BME", and hour is "h" instead of "H"5. McKinney's book was written before that and uses the old names1, so if you follow it you will see deprecation warnings. Use the new ones. Second, "W" and the month end, quarter end and year end rules close the bin on the right and label it on the right by default6, which is why a week appears under its Sunday. Every other rule labels on the left.

Example: Fernhill Home by week and by month

weekly = daily.resample("W").sum(min_count=1)        # weeks Monday to Sunday, labelled by the Sunday
monthly = daily.resample("MS").sum(min_count=1)      # months labelled by the 1st
print(weekly.head(2).round(0))
print(monthly.tail(3).round(0))
# 2023-01-01     6784.0
# 2023-01-08    42308.0
# ...
# 2025-07-01    223123.0
# 2025-08-01    231082.0
# 2025-09-01    177136.0

Two traps sit in these few lines. The first "week" is £6,784, because 1 January 2023 was a Sunday, so the week ending on it contains one day. And September 2025 shows £177,136, about £50,000 below August, because the data stops on the 21st. Neither is a business event. Both are partial periods.

Example: keeping only complete periods

The fix is to count how many days went into each bin and keep the bins that are full.

days_seen = daily.resample("MS").count()
days_in_month = days_seen.index.days_in_month
complete = monthly[days_seen.to_numpy() == days_in_month]
print(days_seen.tail(2).to_dict())
print(complete.index.max().date())
# {2025-08-01: 31, 2025-09-01: 21}
# 2025-08-01

week_days = daily.resample("W").count()
weekly_complete = weekly[week_days == 7]
print(weekly.index[0].date(), week_days.iloc[0], weekly_complete.index[0].date())
# 2023-01-01 1 2023-01-08

count() counts values that are not missing, so a month with the lost export day also fails the test. That is deliberate for charts of totals: a total of 30 days next to totals of 31 is not a fair bar. (You will see in the year over year section that a matched comparison can use such months safely.) Keep the partial month in a separate "month to date" figure, clearly labelled, rather than in the series.

ISO weeks: when "week 1" starts in December

Many teams talk in week numbers. The ISO 8601 standard defines them: weeks start on Monday, and week 1 is the week that contains the first Thursday of the year. That means the last days of December can belong to week 1 of the next ISO year, and the first days of January can belong to week 52 or 53 of the previous one. pandas exposes this through isocalendar()7.

Example: the turn of the year 2024 to 2025

iso = daily.index.isocalendar()
print(iso.loc["2024-12-29":"2025-01-02"])
#             year  week  day
# date
# 2024-12-29  2024    52    7
# 2024-12-30  2025     1    1
# 2024-12-31  2025     1    2
# 2025-01-01  2025     1    3
# 2025-01-02  2025     1    4

by_iso = daily.groupby([iso["year"], iso["week"]]).sum(min_count=1)
print(by_iso.loc[(2025, 1)].round(0))
# 63194.0

ISO week 1 of 2025 began on Monday 30 December 2024. If you group by (calendar year, ISO week) instead of (ISO year, ISO week), those two December days end up in "2024, week 1" next to the first days of January 2024, a full year away. Always pair the ISO week with the ISO year. Week 1 of 2025 is also full of post Christmas sales, which is worth knowing before anyone compares "week 1" across years.

Periods: a month as a thing, not a date

A Timestamp is a point. A Period is a span: the month of November 2024, the quarter Q4 2024. For reporting, a period is often the more honest label, because the month really is the whole month, not its first or last day.

Example: turning month labels into periods

m = monthly.to_period("M")
print(m.index[:2])
# PeriodIndex(['2023-01', '2023-02'], dtype='period[M]', name='date')

p = pd.Period("2024-11", freq="M")
print(p.start_time.date(), p.end_time.date(), p.days_in_month)
# 2024-11-01 2024-11-30 30

Note the small inconsistency in pandas 2.3: for a period the monthly alias is still "M", while for resampling to month end it is now "ME". The period simply means "month", there is no start or end to choose.

Upsampling: spreading a monthly budget over days

Upsampling goes the other way, from coarse to fine. You need it when a plan arrives as monthly totals and the analysis is daily, for example Grace's Meta budget for the last quarter of 2025: £12,000 in October, £15,000 in November, £9,000 in December. Tariq wants a daily planned spend to set against daily revenue.

Example: the forward fill that multiplies the budget

plan = pd.Series([12000.0, 15000.0, 9000.0],
                 index=pd.to_datetime(["2025-10-01", "2025-11-01", "2025-12-01"]))
wrong = plan.resample("D").ffill()
print(round(wrong["2025-10"].sum()))
# 372000

Forward fill (ffill) copies the last known value into the new rows. For a level, such as a price or a stock count, that is right. For a total it is wrong: every October day now carries the whole month's £12,000, and October sums to £372,000. The fix is to copy the value and divide by the number of days in its month. Note also that resample stops at 1 December, the last label, so the December days must be added explicitly.

end = pd.Timestamp("2025-12-31")
daily_plan = plan.reindex(pd.date_range(plan.index.min(), end, freq="D")).ffill()
daily_plan = daily_plan / daily_plan.index.days_in_month
print(round(daily_plan["2025-10-01"], 2), round(daily_plan.resample("MS").sum()).to_dict())
# 387.1 {2025-10-01: 12000.0, 2025-11-01: 15000.0, 2025-12-01: 9000.0}

£387.10 a day in October, and the monthly sums come back to exactly the plan. That last check, resample the result back and compare with the input, is the one I would never skip. An even daily split is itself an assumption, of course. If Grace plans to spend more around Black Friday, the daily plan should follow her plan, not the calendar.

The comparison, part one: shift and percentage change

shift(n) moves the values n rows down, so each row can see the row before it. pct_change(n) is the shortcut for "this value divided by the value n rows earlier, minus one". In pandas 2.1 the old automatic filling of gaps inside pct_change was deprecated8, so I pass fill_method=None to make it explicit that a gap stays a gap.

Example: week on week growth on complete weeks

wow = weekly_complete.pct_change(fill_method=None)
print((wow.tail(3) * 100).round(1))
# 2025-09-07    5.3
# 2025-09-14    6.1
# 2025-09-21   -2.2

lag = pd.DataFrame({"this_week": weekly_complete, "last_week": weekly_complete.shift(1)})
print(lag.tail(2).round(0))
#             this_week  last_week
# 2025-09-14    60662.0    57166.0
# 2025-09-21    59308.0    60662.0

Week on week growth is honest only on complete weeks, which is why Tariq uses weekly_complete. And it is noisy: +5.3%, +6.1% and minus 2.2% in three weeks of September, with nothing changing in the business. That is the reason for the next tool.

One warning about shift. It moves rows, not time. On a series with a missing row, shift(7) compares with whatever sits seven rows up, which may be eight days ago. On a complete daily index it is safe. On anything else, use shift(7, freq="D"), which moves the dates instead of the rows and then lines the values up by date.

The comparison, part two: rolling windows

A rolling window computes a statistic over the last n observations, at every point. A 7 day rolling average removes the weekday pattern. A 28 day rolling average does that too (28 is four whole weeks, so every weekday appears exactly four times) and also smooths away most of the day to day noise. That is why I prefer 28 days to 30 for daily shop data: 30 days contains some weekdays five times and others four, so the average wobbles with the calendar.

The formula is the plain mean of the last 28 days, see Foundations: the mean:

Rˉt=128∑k=027Rt−k\bar{R}_t = \frac{1}{28} \sum_{k=0}^{27} R_{t-k}

where Rˉt\bar{R}_t is the 28 day rolling average on day tt, Rt−kR_{t-k} is the revenue kk days before day tt, and kk runs from 00 (day tt itself) to 2727. For Fernhill Home on 31 August 2025, the 28 days from 4 to 31 August sum to £210,618:

Rˉ31 Aug=210,61828=7,522\bar{R}_{\text{31 Aug}} = \frac{210{,}618}{28} = 7{,}522

with Rˉ31 Aug\bar{R}_{\text{31 Aug}} in pounds, so the 28 day average stands at £7,522 a day.

Example: three ways to roll, and two of them fail quietly

roll7 = daily.rolling(7, min_periods=7).mean()
roll28 = daily.rolling("28D").mean()
roll28_strict = daily.rolling(28, min_periods=28).mean()
print(roll28.head(2).round(0).to_dict())
# {2023-01-01: 6784.0, 2023-01-02: 7992.0}
print(roll28_strict.first_valid_index().date())
# 2023-01-28
print(roll28_strict["2024-03-20":"2024-03-20"].round(0).to_dict(), roll28["2024-03-20":"2024-03-20"].round(0).to_dict())
# {2024-03-20: nan} {2024-03-20: 6777.0}
print(daily.rolling(28, min_periods=28).count()["2024-03-20"])
# 27.0

There are two kinds of window. rolling(28) counts rows. rolling("28D") covers a span of time, the 28 days up to and including each date, however many rows that is9. Each fails in its own way:

  • The time based window "28D" defaults to min_periods=19. So the "28 day average" on 1 January 2023 is the average of one day, and on 2 January of two days. A dashboard that starts its line on day one shows four weeks of a jumpy line that pretends to be smooth.
  • The row based window with min_periods=28 refuses to produce a value whenever one of the 28 days is missing. The lost export day of 12 March 2024 blanks out the average for the following four weeks.

The answer is a time based window with an explicit minimum, which tolerates a gap or two and still refuses to average a handful of days:

roll28 = daily.rolling("28D", min_periods=25).mean()
print(roll28.first_valid_index().date())
# 2023-01-25
print(roll28.loc[["2024-11-28", "2024-12-02", "2025-08-31"]].round(0).to_dict())
# {2024-11-28: 10643.0, 2024-12-02: 12661.0, 2025-08-31: 7522.0}

The average runs from £10,643 the day before Black Friday 2024 to £12,661 on Cyber Monday, and sits at £7,522 at the end of August 2025.

Daily revenue swings between about £5,700 and £10,000 on ordinary days outside November and December, spikes to £31,360 on Black Friday, 29 November 2024, and drops to £3,284 on Christmas Day. The 28 day rolling average climbs from £6,773 on 1 September 2024 to a peak of £13,223 on 16 December 2024, then settles around £7,500 by the end of August 2025. Tap or click to enlarge

The chart shows why the average exists. The daily line is dominated by Black Friday and Christmas, and on ordinary days it swings by thousands of pounds between a Monday and a Saturday. The 28 day line shows the shape of the year: the climb through autumn, the peak in mid December, the January drop, the flat summer. If you present this, the chapter on words on charts explains how to label the two events instead of leaving the reader to guess.

Exponentially weighted and expanding windows

Two relatives of the rolling window are worth knowing. An exponentially weighted moving average (ewm) gives every past day a weight that shrinks the further back it is, so it reacts faster to a change than a plain average of the same length. An expanding window grows from the start of the series (or of each group) to the current row, which gives you running totals and records.

Example: a faster average, year to date, and the best day so far

ewm28 = daily.ewm(span=28, adjust=False, ignore_na=True).mean()
print(ewm28.loc[["2024-11-28", "2024-12-02"]].round(0).to_dict())
# {2024-11-28: 10918.0, 2024-12-02: 14113.0}

ytd = daily.groupby(daily.index.year).cumsum()
print(ytd.loc[["2024-08-31", "2025-08-31"]].round(0).to_dict())
# {2024-08-31: 1660792.0, 2025-08-31: 1792340.0}

best = daily.expanding().max()
print(best.loc["2025-08-31"].round(0), daily.idxmax().date())
# 31360.0 2024-11-29

Over the four days from 28 November to Cyber Monday the exponentially weighted average jumps from £10,918 to £14,113, while the plain 28 day average moves from £10,643 to £12,661. That speed is the reason to use it for alerts ("revenue is moving away from normal") and the reason not to use it for a board chart, where a plain average is easier to explain. Year to date revenue at the end of August is £1,792,340 in 2025 against £1,660,792 in 2024, which is the most robust growth number in the whole chapter: +7.9%, with no weekday or event problem, because eight months of days are compared with eight months of days. The best day ever is still Black Friday 2024 at £31,360.

groupby(...).cumsum() is the pattern for "to date" figures: group by the period that resets the total (year, month, financial year) and sum cumulatively within it. The group by chapter covers the grouping itself.

The comparison, part three: year over year that tells the truth

Year over year growth is the number every founder asks for, and the easiest one to get wrong. The general formula is the plain percentage change, see Foundations: percentages:

g=RthisRlast−1g = \frac{R_{\text{this}}}{R_{\text{last}}} - 1

where gg is the growth rate, RthisR_{\text{this}} is revenue in the period this year and RlastR_{\text{last}} is revenue in the comparison period last year. The whole difficulty sits in the words "comparison period". There are three choices.

Example: the naive calendar comparison

yoy_naive = monthly.pct_change(12, fill_method=None)
print((yoy_naive["2024-02":"2024-03"] * 100).round(1).to_dict())
# {2024-02-01: 14.8, 2024-03-01: 1.4}
print((yoy_naive["2024-09":"2025-09"] * 100).round(1).to_dict())
# {2024-09-01: 8.7, 2024-10-01: 7.7, 2024-11-01: 0.1, 2024-12-01: 17.3,
#  2025-01-01: 7.3, 2025-02-01: 3.5, 2025-03-01: 13.1, 2025-04-01: 4.7,
#  2025-05-01: 7.6, 2025-06-01: 7.5, 2025-07-01: 7.9, 2025-08-01: 11.5, 2025-09-01: -24.5}

The underlying business grows about 7% a year, smoothly. The naive figures say otherwise, and every odd one has a calendar cause:

  • February 2024: +14.8%. 2024 was a leap year. February 2024 had 29 days, February 2023 had 28. One extra day, worth £7,825, is about 5 points of "growth". Worked through: 183,817/160,125−1=14.8%183{,}817 / 160{,}125 - 1 = 14.8\%.
  • March 2024: +1.4%, then March 2025: +13.1%. The lost export day. March 2024 is short by about £8,000, which makes March 2024 look weak and March 2025 look strong. One broken export, two wrong months.
  • November 2024: +0.1%, December 2024: +17.3%. Black Friday moved. More on that below.
  • September 2025: minus 24.5%. A partial month compared with a full one.

Example: matching each day with the same weekday a year earlier

The fix for ordinary days is to compare each day with the day exactly 364 days earlier. 364 is 52 weeks, so a Monday is compared with a Monday, and the leap day takes care of itself. Then sum only the pairs where both days exist, and compute growth from those sums. The comparison period is now "the same weekdays, 52 weeks ago". It is still the percentage change from Foundations: percentages, only with a better denominator.

gM=∑t∈MRt∑t∈MRt−364−1g_M = \frac{\sum_{t \in M} R_t}{\sum_{t \in M} R_{t-364}} - 1

where gMg_M is the aligned growth for month MM, tt runs over the days of MM for which both RtR_t and Rt−364R_{t-364} exist, RtR_t is revenue on day tt, and Rt−364R_{t-364} is revenue on the same weekday 52 weeks earlier. For February 2024 the matched days sum to £183,817 this year against £169,005 a year earlier:

gFeb 2024=183,817169,005−1=0.088g_{\text{Feb 2024}} = \frac{183{,}817}{169{,}005} - 1 = 0.088

with gFeb 2024g_{\text{Feb 2024}} as a share, so +8.8% instead of the naive +14.8%.

pairs = pd.DataFrame({"now": daily, "year_ago": daily.shift(364, freq="D")})
pairs = pairs.dropna()                      # a day only counts if both sides exist
pairs = pairs.loc["2024-01-01":]            # the first year that has a full year before it
agg = pairs.resample("MS").sum()
yoy_aligned = agg["now"] / agg["year_ago"] - 1
print((yoy_aligned * 100).round(1).to_dict())
# {2024-01-01: 7.3, 2024-02-01: 8.8, 2024-03-01: 6.0, 2024-04-01: 7.9, ...
#  2024-11-01: 0.6, 2024-12-01: 18.4, 2025-01-01: 8.6, 2025-02-01: 7.2,
#  2025-03-01: 8.6, ..., 2025-08-01: 10.6, 2025-09-01: 6.3}

Three of the four problems are gone. February is +8.8%. March 2024 is +6.0% and March 2025 +8.6%, because the lost day and its partner a year later both drop out of the sums. And September 2025 is +6.3%, a fair month to date figure, because only the 21 days that exist this year are compared with their 21 partners last year. shift(364, freq="D") moves dates, not rows, so the gap cannot misalign anything.

But November and December are still wrong: +0.6% and +18.4%.

Monthly year over year revenue growth from September 2024 to August 2025. Naive calendar comparison: 8.7, 7.7, 0.1, 17.3, 7.3, 3.5, 13.1, 4.7, 7.6, 7.5, 7.9 and 11.5 percent. Weekday aligned comparison: 7.5, 6.0, 0.6, 18.4, 8.6, 7.2, 8.6, 5.0, 8.2, 6.8, 7.9 and 10.6 percent. Alignment fixes March, but November and December stay distorted because Black Friday moved. Tap or click to enlarge

The Black Friday shift

Black Friday is the Friday after the fourth Thursday in November, the US Thanksgiving holiday10. In 2023 that was 24 November, in 2024 it was 29 November. Cyber Monday followed on 27 November 2023 and on 2 December 2024. So in 2024 the Saturday after Black Friday was the last day of November, and Sunday and Cyber Monday fell in December.

Weekday alignment does not help, because Black Friday 2024 was 371 days after Black Friday 2023, not 364. Fifty two weeks before 29 November 2024 is 1 December 2023, an ordinary Friday. The event moves against the weekday grid in some years, and Easter moves even further (31 March in 2024, 20 April in 2025). For moving events you need a third comparison: the event against the event.

Example: cyber week against cyber week

def cyber_week(black_friday):
    bf = pd.Timestamp(black_friday)
    return daily[bf - pd.Timedelta(days=7): bf + pd.Timedelta(days=3)].sum()

cw23, cw24 = cyber_week("2023-11-24"), cyber_week("2024-11-29")
print(round(cw23), round(cw24), f"{cw24 / cw23 - 1:.1%}")
# 172833 182720 5.7%

nd23 = daily["2023-11-01":"2023-12-31"].sum()
nd24 = daily["2024-11-01":"2024-12-31"].sum()
print(round(nd23), round(nd24), f"{nd24 / nd23 - 1:.1%}")
# 643937 695579 8.0%

rest23 = nd23 - cw23
rest24 = nd24 - cw24
print(f"{rest24 / rest23 - 1:.1%}")
# 8.9%

Now the story is clear, and it is a different story from either monthly chart. The cyber week (the seven days before Black Friday, Black Friday itself and the three days to Cyber Monday) grew 5.7%, from £172,833 to £182,720. November and December together grew 8.0%. The rest of the season, outside the event, grew 8.9%. In other words: the event grew more slowly than the business around it. That is a real question for Grace and Tariq (were the discounts too shallow, did the ads start too late, is the customer simply less driven by the event?), and neither the flat November nor the booming December would ever have raised it.

My rule of thumb from this: align by weekday for ordinary days, by event for event days, and by season when you report to the board. "November and December together, +8.0%" is a figure nobody can misread.

Business days and holidays

Some questions run on working days, not calendar days. When will an order placed on Friday evening be dispatched? How many dispatch days does December have? A shop sells every day, but the warehouse works Monday to Friday and stops on bank holidays, and in England and Wales those are set by proclamation and published by the government11.

You can type the list by hand, and for one year that is fine. For several years and several countries the holidays package is less error prone. It computes the public holidays for a country and, where they differ, for its regions12. In the UK the regions matter: Scotland and Northern Ireland have different bank holidays from England and Wales.

Example: the dispatch calendar for York

import holidays
bank = holidays.country_holidays("GB", subdiv="ENG", years=[2023, 2024, 2025])
print(sorted(d for d in bank if d.year == 2025))
# [2025-01-01, 2025-04-18, 2025-04-21, 2025-05-05, 2025-05-26, 2025-08-25, 2025-12-25, 2025-12-26]

bday = pd.offsets.CustomBusinessDay(holidays=list(bank))
print(pd.Timestamp("2025-08-22") + bday, pd.Timestamp("2025-08-22") + 2 * bday)
# 2025-08-26 00:00:00 2025-08-27 00:00:00

work = pd.bdate_range("2024-12-01", "2024-12-31", freq="C", holidays=list(bank))
print(len(work))
# 20
print(np.busday_count("2025-08-01", "2025-09-01", holidays=list(bank)))
# 20

CustomBusinessDay is an offset that skips weekends and the holidays you give it. An order placed on Friday 22 August 2025 is dispatched, one working day later, on Tuesday 26 August, because Monday 25 August was the summer bank holiday. pd.bdate_range with freq="C" lists the working days of a span: December 2024 had 20, after Christmas Day and Boxing Day. NumPy's busday_count gives the same count without building the dates, and it says August 2025 also had 2013.

The same flags are useful beyond dispatch. A column "is this day a bank holiday" is one of the first things a forecasting model wants, and counting trading days per month is the classic calendar adjustment before comparing monthly totals14.

Seasonality: a preview

Rolling averages and aligned comparisons work around seasonality. Measuring it is the next step, and it belongs to the forecasting chapter of the Marketing analytics in Python series, which builds on everything here. As a taste, the weekday pattern is a single group by.

Example: the weekday pattern in 2025

profile = daily["2025-01-01":"2025-08-31"].groupby(daily["2025-01-01":"2025-08-31"].index.day_name()).mean()
order = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
print((profile[order] / profile.mean()).round(2).to_dict())
# {'Monday': 1.11, 'Tuesday': 1.05, 'Wednesday': 1.0, 'Thursday': 0.99,
#  'Friday': 0.94, 'Saturday': 0.87, 'Sunday': 1.03}

Monday is 11% above an average day, Saturday 13% below. That index is exactly what a 7 or 28 day window averages away, and exactly what a naive day on day comparison mistakes for news. A "Saturday dip" alert would fire every week. Seasonality within the year (the quiet summer, the busy winter) works the same way at monthly scale, with the added problem that you have only two or three examples of each month. The data storytelling chapter on showing time shows how to chart both, and statistical thinking for growth explains why one week's average rarely means what it seems to.

What Tariq can now tell Grace

Tariq's standing question was which channel pays back and what to do with next month's budget. This chapter does not answer it yet, but it removes the calendar from the answer. With one local clock, complete periods, gaps treated as gaps and aligned comparisons, he can say:

  • the business grows about 8% a year, measured three ways that agree (year to date +7.9%, November and December together +8.0%, aligned monthly growth between 5% and 11%);
  • September is on track at +6.3%, month to date, matched day by day;
  • last year's cyber week grew more slowly than the rest of the season, which is the first real question for this year's Black Friday budget.

Those three lines are what the next chapters build on: joining this daily series with daily ad spend by channel, charting it, and modelling it. If you would rather have this pipeline built and maintained for your own shop, this is the kind of work my Data Science service covers.

A checklist for every time series

CheckHow in pandasWhat goes wrong without it
Parse timestamps with their zonepd.to_datetime(..., utc=True)Dates shift by an hour in summer
Convert once, to the shop's local zone.dt.tz_convert("Europe/London")Shop and GA4 disagree on daily totals
Treat empty days as gaps.resample("D").sum(min_count=1)A lost export becomes a day of zero sales
Check every day is presentreindex on a full date_rangeMissing rows shift every shift and rolling window
Drop or label partial periodscount() against days_in_monthA short month looks like a crash
Use the current aliases"ME", "QE", "YE", "h"Deprecation warnings, later errors
Pair ISO weeks with ISO yearsisocalendar() year and weekLate December lands a year away
Divide totals when upsamplingDivide by days_in_monthA monthly budget multiplied by 30
Set the window's minimumrolling("28D", min_periods=25)A "28 day average" of one day
Compare by weekday, event and seasonshift(364, freq="D"), event windowsLeap years and Black Friday read as growth

My view

My view: in a business time series the date logic matters more than the method. A forecasting model on a series with UTC days, a zero for a lost export and a partial month at the end will produce a confident wrong answer, and a plain 28 day average on a clean series will beat it. So I would spend the first hour of any time series work on the three decisions (clock, calendar, comparison), write them in a short note at the top of the notebook, and only then start computing.

I would also stop reporting single calendar months year over year to anyone who decides budgets. Report the aligned figure, report the event against the event, and report the season. The extra effort is a dozen lines of pandas, written once. The cost of not doing it is a board that cut a November budget because "November was flat" when the business grew 8%.

If you want to work through your own shop's exports this way, the free workshop is the place to start, and the first two weeks of work are on me.

Conclusion

Time series in pandas come down to three decisions. The clock: parse every timestamp with its zone, store in UTC, and convert once to the shop's local time before you form days. The calendar: resample with the right rule and know how it labels, treat empty days as gaps with min_count=1, keep partial weeks and months out of charts of totals, pair ISO weeks with ISO years, and divide totals when you upsample. The comparison: use rolling windows over 7 or 28 days with an explicit minimum, compare days with the same weekday 52 weeks earlier, compare moving events with themselves, and use year to date or the whole season when the answer has to be unambiguous.

The next chapter of the series turns these series into charts, and the statistical models chapter after it starts explaining them.

If your shop export, GA4 and ad reports never agree on a day's revenue, bring them to the free workshop and we sort out the clock, the calendar and the comparison together. The first two weeks of work are on me.

Sources

  1. 1.

    Wes McKinney, Python for Data Analysis, 3rd edition, chapter 11 "Time Series", O'Reilly, 2022, free online edition, https://wesmckinney.com/book/time-series.html

  2. 2.

    pandas development team, Time series / date functionality, pandas 2.3 user guide, section on time zone handling, 2025, https://pandas.pydata.org/pandas-docs/version/2.3/user_guide/timeseries.html

  3. 3.

    Google, BigQuery Export schema (fields event_date and event_timestamp), Analytics Help, https://support.google.com/analytics/answer/7029846

  4. 4.

    Google, About your language, number format, time zone and currency settings, Google Ads Help, https://support.google.com/google-ads/answer/9842104

  5. 5.

    pandas development team, What's new in 2.2.0: deprecate aliases M, Q, Y in favour of ME, QE, YE, January 2024, https://pandas.pydata.org/pandas-docs/version/2.3/whatsnew/v2.2.0.html

  6. 6.

    pandas development team, pandas.DataFrame.resample, parameters closed and label, pandas 2.3 API reference, https://pandas.pydata.org/pandas-docs/version/2.3/reference/api/pandas.DataFrame.resample.html

  7. 7.

    pandas development team, pandas.Series.dt.isocalendar, pandas 2.3 API reference, https://pandas.pydata.org/pandas-docs/version/2.3/reference/api/pandas.Series.dt.isocalendar.html

  8. 8.

    pandas development team, What's new in 2.1.0: deprecated fill_method and limit keywords in pct_change, August 2023, https://pandas.pydata.org/pandas-docs/version/2.3/whatsnew/v2.1.0.html

  9. 9.

    pandas development team, pandas.DataFrame.rolling, parameter min_periods, pandas 2.3 API reference, https://pandas.pydata.org/pandas-docs/version/2.3/reference/api/pandas.DataFrame.rolling.html

  10. 10.

    United States Code, Title 5, section 6103, Holidays (Thanksgiving Day, the fourth Thursday in November), Legal Information Institute, Cornell Law School, https://www.law.cornell.edu/uscode/text/5/6103

  11. 11.

    GOV.UK, UK bank holidays, https://www.gov.uk/bank-holidays

  12. 12.

    holidays package, version 0.81, Python Package Index, 15 September 2025, https://pypi.org/project/holidays/0.81/

  13. 13.

    NumPy developers, numpy.busday_count, NumPy 2.3 reference, https://numpy.org/doc/2.3/reference/generated/numpy.busday_count.html

  14. 14.

    Rob J Hyndman and George Athanasopoulos, Forecasting: Principles and Practice, 3rd edition, section 3.1 "Transformations and adjustments" (calendar adjustments), OTexts, 2021, https://otexts.com/fpp3/transformations.html

Shelter

I’m running the London Marathon for Shelter. Sunday 25 April 2027

My personal fundraiser. Shelter, the National Campaign for Homeless People Limited, registered charity 263710 (England and Wales) and SC002327 (Scotland), registered with the Fundraising Regulator.

Donate to Shelter