Python CSV Monthly Totals: Stop Different Years From Merging Into One Month
Have you ever aggregated a multi-year transaction CSV by month and wondered why February's sales suddenly looked double?
Grouping by dt.month alone strips out the year—silently combining 2025-02 and 2026-02 into the same bucket.
1. Sample CSV (sales.csv)
date,amount
2025-02-10,100
2026-02-14,120
2026-03-01,80
2. The Buggy Approach (Grouping by dt.month)
import csv
from collections import defaultdict
from datetime import datetime
totals = defaultdict(int)
with open("sales.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
dt = datetime.strptime(row["date"], "%Y-%m-%d")
totals[dt.month] += int(row["amount"]) # BUG: loses the year!
print(dict(totals))
# {2: 220, 3: 80} <-- 2025-02 and 2026-02 merged!
3. The Fix: Group by %Y-%m (Year + Month)
import csv
from collections import defaultdict
from datetime import datetime
totals = defaultdict(int)
with open("sales.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
dt = datetime.strptime(row["date"], "%Y-%m-%d")
key = dt.strftime("%Y-%m") # "2025-02", "2026-02"
totals[key] += int(row["amount"])
for ym in sorted(totals):
print(f"{ym}: {totals[ym]}")
Output:
2025-02: 100
2026-02: 120
2026-03: 80
Because YYYY-MM sorts chronologically as plain strings, sorted(totals) automatically prints every month in order.
Comments
Post a Comment