Use zoneinfo, not a naive datetime
A naive datetime is a wall-clock reading with no location. Attaching a raw offset (-05:00) says what the clock was but not what rule produced it, so it cannot answer "what is the local time next week?" Use an IANA zone object end to end.
Procedure
- Use
zoneinfo.ZoneInfo(Python 3.9+) which reads the system tzdata and honours DST rules:
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
now = datetime.now(timezone.utc) # aware, UTC
tokyo = now.astimezone(ZoneInfo("Asia/Tokyo")) # aware, Tokyo rules
- Attach zones at the boundary where a human gives you a local time, and never earlier:
meeting = datetime(2026, 3, 1, 9, 0, tzinfo=ZoneInfo("Europe/London"))
- Convert, do not re-attach.
dt.replace(tzinfo=tz)relabels a wall clock;dt.astimezone(tz)converts an instant:
wrong = now.replace(tzinfo=ZoneInfo("Asia/Tokyo")) # same digits, wrong instant
right = now.astimezone(ZoneInfo("Asia/Tokyo")) # correct instant
- Store the zone name a user chose, not the offset, so future conversions survive DST:
user_prefs = {"timezone": "America/New_York"} # never "-05:00"
- Ban naive construction in review: grep for
datetime.now()anddatetime(...)withouttzinfo:
rg -n 'datetime\.now\(\)|datetime\.utcnow|date\.today\(\)' src/
utcnow() returns a naive object — use datetime.now(timezone.utc).
6. If you must use a third-party library, prefer zoneinfo; for legacy pytz, use pytz.timezone(z).localize(naive), never tzinfo= at construction.
7. Serialise with .isoformat() (keeps offset) and parse back with an aware parser.
Pitfalls
datetime.now()on a host set toUTClooks correct in tests and returns local time in production; usedatetime.now(timezone.utc).- Comparing aware and naive datetimes raises
TypeError; two libraries each producing their own kind is a common integration failure. dateutil.tz.gettzandzoneinfocan disagree if the vendored tzdata is stale; pick one source of zone truth.pandastimestamps are tz-aware butSeries.dt.tz_localizevstz_convertare easy to swap —localizeon an already-aware series raises.- A fixed offset
+05:30cannot express that India never shifts; a zone can. Offsets are for display of a known instant, zones for computation.
Verification
python3 -c "from datetime import datetime, timezone; from zoneinfo import ZoneInfo; n=datetime.now(timezone.utc); print(n.astimezone(ZoneInfo('Asia/Tokyo')).utcoffset())"
Prints 9:00:00 = Tokyo rules applied to a UTC instant. Report: "all datetimes are zone-aware; grep for naive constructors returns 0 hits outside tests."