Python TypeError: can't compare offset-naive and offset-aware datetimes — the one conversion you actually need
Problem
A daily report job crashed the first time it met a timestamp from the new "timezone-aware" column:
TypeError: can't compare offset-naive and offset-aware datetimes
File "/app/src/tasks/daily_report.py", line 41, in run
if event.occurred_at >= window_start:event.occurred_at was aware (read from a timestamptz column); window_start was naive (datetime.now() — no tzinfo). Python refuses to guess which timezone the naive one means.
Root cause
Python datetime objects carry an optional tzinfo, and comparison/substraction requires both sides to agree on whether time is anchored. datetime.now() is naive local-ish time; datetime.utcnow() is naive UTC; datetime.now(timezone.utc) is aware UTC. The three are different values, and mixing any two produces either this TypeError or — worse — silently wrong windows (the naive-vs-naive case where someone mixed utcnow() with local now() and the report was off by the UTC offset forever).
from datetime import datetime, timezone, timedelta
window_start = datetime.now(timezone.utc) - timedelta(hours=24)
… 1 more line in the fix🔒 the fix — including 4 code blocks — is members-only. $1/mo unlocks everything.