Skip to main content

Data analysis · Intermediate · 22 min

Work with dates and time series in pandas

By Padding · Updated 18 Nov 2026
Python 3.15 · pandas 3.1.1 · tzdata 2026.6 · uv 0.13 (checked on python:3.15-slim)

You will turn fifteen months of hourly electricity-meter readings with gaps into clean daily and monthly totals in pandas 3.1, with flagged and filled missing hours, rolling averages, week-on-week and year-on-year comparisons, correct Africa/Lagos and UTC times, and no month-end surprises.

On this page

Time series look easy until the first real file arrives. Timestamps come in as text in someone else's format, the device skipped a few hours when its connection dropped, one hour arrived twice, and nobody wrote down which time zone the clock was set to. Every total you build on top of that inherits the mess.

In this tutorial you work on fifteen months of hourly readings from a household electricity meter in Lagos, from 1 January 2025 to 31 March 2026. You generate the file yourself, so your numbers will match the ones shown here. By the end you have:

  • a DatetimeIndex parsed from day-first text, with the duplicate removed
  • the times pinned to Africa/Lagos and stored as UTC
  • every missing hour found, short gaps filled and long gaps left empty and flagged
  • daily and monthly totals that do not pretend an empty day used zero electricity
  • 7-day rolling averages, day-on-day and week-on-week changes
  • one week in March 2026 compared with the same week a year earlier, Monday against Monday
  • a short list of month-end traps and the code that avoids them

The meter data is made up, but the problems are the ones real loggers produce. Meters that report over mobile data often go quiet for a few hours when the connection drops or the data bundle runs out, which is why gap handling gets a whole step.

Step 1 · Create the project and generate the readings

Make a throwaway project folder and add pandas, kept to the 3.1 series so a new minor release cannot change results under you. tzdata gives Python the IANA time zone database on systems that have none, such as Windows and some minimal Linux images:

Bash
mkdir -p ~/meter-demo
cd ~/meter-demo
uv init --no-package --python 3.15
uv add "pandas>=3.1,<3.2" "tzdata>=2026.6"

Now write a script that creates the raw file. It builds a daily load shape (low overnight, a morning bump, an evening peak), raises it in the hot months and at weekends, adds 8% in 2026 for a new freezer, then removes five stretches of hours and sends one hour twice. Timestamps are written the way many loggers in Nigeria and the UK write them: day first, local wall-clock time, no offset.

Bash
cd ~/meter-demo
cat > make_readings.py <<'PY'
import csv
from datetime import datetime, timedelta
from pathlib import Path

# kWh used in each hour of the day: low overnight, a morning bump, an evening peak
PROFILE = [0.4, 0.4, 0.4, 0.4, 0.4, 0.5, 0.9, 1.2, 1.0, 0.8, 0.8, 0.9,
           1.0, 0.9, 0.8, 0.8, 0.9, 1.3, 1.6, 1.7, 1.5, 1.2, 0.8, 0.5]
# Hotter months mean more fans and air conditioning
SEASON = {1: 1.00, 2: 1.10, 3: 1.20, 4: 1.20, 5: 1.10, 6: 1.00,
          7: 0.95, 8: 0.95, 9: 1.00, 10: 1.05, 11: 1.05, 12: 1.00}
# Hours the logger lost its connection: (first missing hour, length in hours)
GAPS = [("2025-03-10 09:00", 6), ("2025-07-21 02:00", 2), ("2025-11-04 18:00", 1),
        ("2026-02-15 00:00", 24), ("2026-03-04 13:00", 3)]

missing = set()
for first, hours in GAPS:
    start = datetime.strptime(first, "%Y-%m-%d %H:%M")
    missing.update(start + timedelta(hours=h) for h in range(hours))

rows = []
t = datetime(2025, 1, 1, 0, 0)
while t < datetime(2026, 4, 1, 0, 0):
    if t not in missing:
        kwh = PROFILE[t.hour] * SEASON[t.month]
        kwh += 0.2 if t.weekday() >= 5 else 0.0      # weekends at home
        kwh += ((t.toordinal() * 7) % 5 - 2) * 0.04  # day-to-day wobble
        kwh *= 1.08 if t.year == 2026 else 1.0       # a new freezer in 2026
        rows.append([t.strftime("%d/%m/%Y %H:%M"), f"{kwh:.3f}"])
    t += timedelta(hours=1)

# After reconnecting, the logger sent one hour twice
resent = next(r for r in rows if r[0] == "04/03/2026 16:00")
rows.insert(rows.index(resent) + 1, list(resent))

Path("raw").mkdir(exist_ok=True)
with open("raw/meter_readings.csv", "w", newline="") as f:
    writer = csv.writer(f, lineterminator="\n")
    writer.writerow(["recorded_at", "kwh"])
    writer.writerows(rows)
print("rows written:", len(rows))
PY
uv run make_readings.py
head -4 raw/meter_readings.csv

Check it worked

The script prints rows written: 10885. Fifteen months is 10,920 hours; 36 are missing and one is doubled. head shows the header recorded_at,kwh and rows such as 01/01/2025 00:00,0.480.

Step 2 · Parse the timestamps and set a DatetimeIndex

Read the file and look at the column types before doing anything else:

Bash
cd ~/meter-demo
cat > parse_readings.py <<'PY'
import pandas as pd

raw = pd.read_csv("raw/meter_readings.csv")
print(raw.dtypes.to_string())

raw["recorded_at"] = pd.to_datetime(raw["recorded_at"], format="%d/%m/%Y %H:%M")
readings = raw.set_index("recorded_at").sort_index()

print("index type:", type(readings.index).__name__)
print("first:", readings.index.min(), " last:", readings.index.max())
print("sorted:", readings.index.is_monotonic_increasing)
print("duplicate timestamps:", int(readings.index.duplicated().sum()))
print(readings.loc["2025-03-10 07:00":"2025-03-10 16:00"].to_string())
PY
uv run parse_readings.py

Three things matter here:

  • recorded_at comes in as str, the default text type in pandas 3. A date stored as text cannot be sorted by time or resampled.
  • format="%d/%m/%Y %H:%M" states the order of day and month. Without it, a value like 04/03/2026 could be read as 3 April. With an explicit format, a row that does not match raises an error instead of being guessed.
  • Once the timestamps are the index, you can slice by time with plain strings: "2025-03-10 07:00":"2025-03-10 16:00" picks those hours, and readings.loc["2025-03"] would pick the whole month.

Check it worked

The output shows recorded_at str, then index type: DatetimeIndex, a first stamp of 2025-01-01 00:00:00 and a last of 2026-03-31 23:00:00, sorted: True and duplicate timestamps: 1. The slice for 10 March jumps from 08:00 straight to 15:00: that is the first gap, and you deal with it in a later step.

Step 3 · Attach the Lagos time zone and store UTC

The timestamps so far are naive: they have no time zone. The logger records Lagos wall-clock time, so say so with tz_localize, then convert to UTC with tz_convert for storage. Lagos uses West Africa Time, UTC+1 all year with no daylight saving, so every local hour maps to exactly one UTC hour.

This script also drops the duplicate hour, keeping the first copy, and shows what happens in a zone that does change its clocks:

Bash
cd ~/meter-demo
cat > add_time_zone.py <<'PY'
from pathlib import Path

import pandas as pd

raw = pd.read_csv("raw/meter_readings.csv")
raw["recorded_at"] = pd.to_datetime(raw["recorded_at"], format="%d/%m/%Y %H:%M")
readings = raw.set_index("recorded_at").sort_index()
readings = readings[~readings.index.duplicated(keep="first")]

# The logger writes Lagos wall-clock time with no offset: say so, then store UTC
lagos = readings.tz_localize("Africa/Lagos")
utc = lagos.tz_convert("UTC")
print("Lagos:", lagos.index[0], "| UTC:", utc.index[0])

Path("clean").mkdir(exist_ok=True)
utc.rename_axis("time_utc").to_csv("clean/readings_utc.csv", date_format="%Y-%m-%dT%H:%M:%SZ")
print("rows saved:", len(utc))

# Zones with daylight saving have hours that do not exist, or happen twice
spring = pd.DatetimeIndex(["2026-03-29 01:30"])
try:
    spring.tz_localize("Europe/London")
except ValueError as err:
    print("London:", err)
print("shifted:", spring.tz_localize("Europe/London", nonexistent="shift_forward")[0])
PY
uv run add_time_zone.py
head -3 clean/readings_utc.csv

The first Lagos reading, midnight on 1 January 2025, is 23:00 on 31 December 2024 in UTC. On 29 March 2026 London clocks jump from 01:00 to 02:00, so 01:30 never happened there, and pandas refuses to guess. nonexistent="shift_forward" moves it to the next valid time; for the autumn hour that happens twice, ambiguous="NaT" marks it as unknown. Most African zones have no daylight saving, but not all: Morocco (Africa/Casablanca) moves its clocks back for Ramadan, so never assume a fixed offset from a country name.

Check it worked

You see Lagos: 2025-01-01 00:00:00+01:00 | UTC: 2024-12-31 23:00:00+00:00 and rows saved: 10884 (the duplicate is gone). The London line says 2026-03-29 01:30:00 is a nonexistent time, and the shifted value is 2026-03-29 02:00:00+01:00. The saved file's first data row is 2024-12-31T23:00:00Z,0.48.

Now read the file back, the way any later script will, and see why the zone matters for daily totals:

Bash
cd ~/meter-demo
cat > read_back.py <<'PY'
import pandas as pd

back = pd.read_csv("clean/readings_utc.csv")
back["time_utc"] = pd.to_datetime(back["time_utc"], utc=True)
back = back.set_index("time_utc")
print(back.index.dtype)

daily_utc = back["kwh"].resample("D").sum()
daily_lagos = back["kwh"].tz_convert("Africa/Lagos").resample("D").sum()
print("1 Jan 2025 total, UTC days:  ", round(daily_utc.loc["2025-01-01"], 2))
print("1 Jan 2025 total, Lagos days:", round(daily_lagos.loc["2025-01-01"], 2))
PY
uv run read_back.py

The index type is datetime64[us, UTC]: microsecond resolution, the pandas 3 default, with the zone attached. A UTC day runs from 01:00 to 01:00 Lagos time, so it takes one hour from the next day. Resample in the zone where the day means something to the reader, and store in UTC. The tutorial Store and show dates and times correctly across time zones covers the storage side in databases and APIs.

The two totals differ: 22.9 for the UTC day and 23.02 for the Lagos day.

Step 4 · Find the missing hours and fill only the short gaps

A missing hour does not show up as an empty row; it simply is not there. To see it, build the full list of hours you expect with pd.date_range and reindex onto it. Hours with no reading become NaN.

Then decide what to do with each gap. A one- to three-hour gap in a smooth load curve can be bridged by drawing a straight line between its neighbours (interpolate(method="time")). A whole missing day cannot: inventing 24 hours of readings would be making data up. So the script measures the length of every run of missing hours and fills only runs of three hours or fewer. Everything is flagged, so you can always tell a real reading from a filled one.

Bash
cd ~/meter-demo
cat > fill_gaps.py <<'PY'
import pandas as pd

df = pd.read_csv("clean/readings_utc.csv")
df["time_utc"] = pd.to_datetime(df["time_utc"], utc=True)
kwh = df.set_index("time_utc")["kwh"].tz_convert("Africa/Lagos")

# Every hour that should exist, from the first reading to the last
expected = pd.date_range(kwh.index.min(), kwh.index.max(), freq="h")
hourly = kwh.reindex(expected).to_frame("kwh")
hourly["missing"] = hourly["kwh"].isna()
print("expected hours:", len(expected), "| missing:", int(hourly["missing"].sum()))

# Give each run of missing hours an id, then measure how long each run is
run_id = (hourly["missing"] != hourly["missing"].shift()).cumsum()
run_length = hourly.groupby(run_id)["missing"].transform("size")
gaps = hourly[hourly["missing"]].groupby(run_id[hourly["missing"]]).apply(
    lambda g: pd.Series({"starts": g.index[0], "hours": len(g)})
)
print(gaps.to_string(index=False))

# Fill short gaps (up to 3 hours) by drawing a line between the neighbours;
# leave longer gaps empty and flagged
short_gap = hourly["missing"] & (run_length <= 3)
interpolated = hourly["kwh"].interpolate(method="time")
hourly["kwh"] = hourly["kwh"].where(~short_gap, interpolated)
hourly["filled"] = short_gap
print("filled:", int(hourly["filled"].sum()), "| still empty:", int(hourly["kwh"].isna().sum()))

hourly.rename_axis("time_utc").tz_convert("UTC").to_csv(
    "clean/hourly.csv", date_format="%Y-%m-%dT%H:%M:%SZ"
)
PY
uv run fill_gaps.py

The run_id line is a common trick: it adds one each time the value of missing changes, so every unbroken run of the same value gets its own number. Why not interpolate(limit=3)? Because a limit fills the first three hours of a six-hour gap and leaves the rest, which is worse than either filling or not.

Check it worked

The script reports expected hours: 10920 | missing: 36 and a table of five gaps: 6 hours from 09:00 on 10 March 2025, 2 hours on 21 July, 1 hour on 4 November, all 24 hours of 15 February 2026 and 3 hours on 4 March 2026. It ends with filled: 6 | still empty: 30: the 2-, 1- and 3-hour gaps were bridged, the 6- and 24-hour gaps were not. clean/hourly.csv has 10,920 data rows plus a header.

Step 5 · Resample to daily and monthly totals

Every later step needs to load the hourly file and build daily totals, so put both in a small module:

Bash
cd ~/meter-demo
cat > meter.py <<'PY'
import pandas as pd


def load_hourly():
    """Hourly readings on Lagos time, with the missing and filled flags."""
    df = pd.read_csv("clean/hourly.csv")
    df["time_utc"] = pd.to_datetime(df["time_utc"], utc=True)
    return df.set_index("time_utc").tz_convert("Africa/Lagos").rename_axis("time")


def daily_totals(hourly):
    """One row per Lagos calendar day. kwh is empty unless all 24 hours have a value."""
    return hourly.resample("D").agg(
        kwh=("kwh", lambda s: s.sum(min_count=24)),
        hours=("kwh", "count"),
        filled=("filled", "sum"),
    )
PY

The important part is min_count=24. A plain sum() of a day with no readings returns 0, and a day with 18 of 24 hours returns a total that is quietly too low. Both look like real, low-usage days in a chart. With min_count=24 an incomplete day has no total at all, and the hours column says why.

Monthly totals have the same problem with a twist: months have different lengths, so a 28-day February looks smaller than a 31-day March even at the same daily rate. Count the hours, compare with the hours the month should have, and report a per-day rate alongside the total:

Bash
cd ~/meter-demo
cat > totals.py <<'PY'
from meter import daily_totals, load_hourly

hourly = load_hourly()
daily = daily_totals(hourly)
print(daily.loc["2025-03-09":"2025-03-11"].round(2).to_string())
print(daily.loc["2026-02-14":"2026-02-16"].round(2).to_string())
print("days with no total:", int(daily["kwh"].isna().sum()))

monthly = hourly["kwh"].resample("ME").agg(["sum", "count"])
monthly["complete"] = monthly["count"] == monthly.index.days_in_month * 24
monthly["kwh_per_day"] = monthly["sum"] / monthly["count"] * 24
print(monthly.round(1).to_string())
PY
uv run totals.py

"ME" means month end: each monthly row is labelled with the last day of its month. Filled hours count as recorded, which is why July 2025 shows as complete; use the filled column if you need to report raw readings only.

Check it worked

10 March 2025 shows NaN with 18 hours and 15 February 2026 shows NaN with 0 hours, and the script reports days with no total: 2. In the monthly table, March 2025 and February 2026 are False under complete, with counts of 738 and 648. February 2025 totals 686.4 kWh against January's 694.4, but its per-day rate is higher, 24.5 against 22.4.

Step 6 · Smooth the series and measure changes with shift

Daily totals jump around. A rolling mean smooths that out, and there are two ways to define the window:

  • rolling(7) uses the last 7 rows. One missing value makes the whole window empty, so a single bad day blanks out a week of averages.
  • rolling("7D", min_periods=5) uses the last 7 calendar days and gives a result whenever at least 5 of them have a value. On a series with missing rows, it still means "the past week", not "the past 7 rows".

For changes, diff() gives this day minus the previous one, and shift(7) moves the series down seven rows, so dividing by it compares each day with the same weekday a week earlier. Daily data from resample has one row per day with no holes, which is what makes counting rows safe here.

Bash
cd ~/meter-demo
cat > trends.py <<'PY'
import pandas as pd

from meter import daily_totals, load_hourly

kwh = daily_totals(load_hourly())["kwh"]

trend = pd.DataFrame({"kwh": kwh})
trend["avg_7_rows"] = kwh.rolling(7).mean()
trend["avg_7_days"] = kwh.rolling("7D", min_periods=5).mean()
trend["vs_yesterday"] = kwh.diff()
trend["vs_last_week_pct"] = (kwh / kwh.shift(7) - 1) * 100

window = trend.loc["2026-02-12":"2026-02-23"]
window.index = window.index.strftime("%a %d %b")
print(window.round(2).to_string())
PY
uv run trends.py

Check it worked

Look at the rows from Sunday 15 February, the empty day. avg_7_rows is NaN for seven days in a row, from Sun 15 Feb to Sat 21 Feb, and comes back on Sun 22 Feb. avg_7_days never drops out: it is 25.93 on the 15th itself. vs_yesterday is empty on the 15th and 16th, and vs_last_week_pct is empty on the 15th and again on Sun 22 Feb, which has no value from a week before to compare with. Gaps spread into every calculation that touches them, so decide which behaviour you want before you chart anything.

Step 7 · Compare the same week year on year

Was the first full week of March 2026 heavier than the same week in 2025? "The same week" needs care. Going back one calendar year from Monday 2 March 2026 lands on a Sunday, and households use electricity differently at weekends. Going back 364 days, exactly 52 weeks, lands on Monday 3 March 2025.

shift(freq="364D") moves the timestamps forward instead of moving values between rows, so each 2025 value is labelled with the 2026 date it should be compared with:

Bash
cd ~/meter-demo
cat > same_week.py <<'PY'
import pandas as pd

from meter import daily_totals, load_hourly

daily = daily_totals(load_hourly())

this_week = daily.loc["2026-03-02":"2026-03-08", ["kwh", "filled"]]

# 364 days is exactly 52 weeks, so Monday lines up with Monday
last_year = daily["kwh"].shift(freq="364D")
compare = this_week.assign(last_year=last_year)
compare["change_pct"] = (compare["kwh"] / compare["last_year"] - 1) * 100
compare.index = compare.index.strftime("%a %d %b %Y")
print(compare.round(1).to_string())

total_now, total_then = compare["kwh"].sum(), compare["last_year"].sum()
print(f"week total: {total_now:.1f} kWh vs {total_then:.1f} kWh "
      f"({(total_now / total_then - 1) * 100:+.1f}%)")

monday = pd.Timestamp("2026-03-02")
print("one calendar year back:", (monday - pd.DateOffset(years=1)).strftime("%a %d %b %Y"))
print("52 weeks back:         ", (monday - pd.Timedelta(days=364)).strftime("%a %d %b %Y"))
PY
uv run same_week.py

assign lines the shifted series up by date, so no manual matching is needed. Single days range from roughly level to about 23% up, depending on the day-to-day wobble, but the week as a whole is up 8.8%, close to the 8% the freezer added. Compare whole weeks or longer when daily noise is large. Note that Wednesday 4 March 2026 includes 3 filled hours; say so if you publish the figure.

Check it worked

The table has seven rows from Mon 02 Mar 2026 to Sun 08 Mar 2026, with 3 under filled on Wednesday. The summary line reads week total: 203.3 kWh vs 186.8 kWh (+8.8%), and the last two lines show that one calendar year back is Sun 02 Mar 2025 while 52 weeks back is Mon 03 Mar 2025.

Step 8 · Avoid month-end traps

Months are the unit people report in and the one most likely to break date arithmetic. Run these side by side:

Bash
cd ~/meter-demo
cat > month_ends.py <<'PY'
import pandas as pd

from meter import load_hourly

jan31 = pd.Timestamp("2025-01-31")
print("Jan 31 + 30 days:        ", (jan31 + pd.Timedelta(days=30)).date())
print("Jan 31 + 1 month:        ", (jan31 + pd.DateOffset(months=1)).date())
print("Jan 31 + 1 month, back:  ", (jan31 + pd.DateOffset(months=1) - pd.DateOffset(months=1)).date())
print("Jan 15 + MonthEnd():     ", (pd.Timestamp("2025-01-15") + pd.offsets.MonthEnd()).date())
print("Jan 31 + MonthEnd():     ", (jan31 + pd.offsets.MonthEnd()).date())
print("Jan 31 + MonthEnd(0):    ", (jan31 + pd.offsets.MonthEnd(0)).date())

hourly = load_hourly()
feb_end = pd.Timestamp("2025-02-28", tz="Africa/Lagos")
upto_midnight = hourly.loc[hourly.index <= feb_end]
whole_day = hourly.loc[:"2025-02-28"]
print("hours up to 2025-02-28 00:00:", len(upto_midnight))
print("hours up to the end of 28 Feb:", len(whole_day))

next_month = hourly.loc[hourly.index < feb_end + pd.Timedelta(days=1)]
print("hours before 1 Mar 00:00:   ", len(next_month))

print(hourly["kwh"].resample("MS").sum().head(2).round(1).to_string())
try:
    hourly["kwh"].resample("M").sum()
except ValueError as err:
    print("resample('M') fails:", str(err).split(". ")[0])
PY
uv run month_ends.py

What each line teaches:

  • "A month" is not 30 days. 31 January plus 30 days is 2 March. Use pd.DateOffset(months=1) for calendar months.
  • Month arithmetic does not reverse. 31 January plus a month is 28 February (pandas clips to the last day), and back a month from there is 28 January, not 31.
  • MonthEnd() always moves. From mid-month it goes to the end of that month; from a date already at month end it jumps to the end of the next one. MonthEnd(0) rolls forward only when needed, which is usually what you meant.
  • A date is midnight. Comparing with the timestamp 2025-02-28 keeps only the first hour of that day: 1,393 hours instead of 1,416. The string slice loc[:"2025-02-28"] includes the whole day, and so does < 1 March 00:00. For hourly data, use a half-open range: start inclusive, end exclusive.
  • Pick the label you want. "ME" labels each month with its last day, "MS" with its first. "M" no longer works in pandas 3, so older code and answers that use it fail with Invalid frequency: M.

Check it worked

The output matches the list: 2025-03-02, 2025-02-28, 2025-01-28, then 2025-01-31, 2025-02-28 and 2025-01-31 for the three MonthEnd lines. The hour counts are 1393, 1416 and 1416. The MS table starts 2025-01-01 with 694.4 and 2025-02-01 with 686.4, the same totals as the ME table in an earlier step under different labels. The last line is resample('M') fails: Invalid frequency: M.

When you are done, delete the practice project with rm -rf ~/meter-demo.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.