datetime Basics (Timezones, Pitfalls)
On this page
Naive vs Aware
Timezone bugs are common incident causes. Avoid mixing naive and timezone-aware datetimes.
Prefer UTC Internally
from datetime import datetime, timezone now_utc = datetime.now(timezone.utc) print(now_utc.isoformat())
Parse and Format ISO 8601
from datetime import datetime ts = "2026-02-24T10:30:00+00:00" dt = datetime.fromisoformat(ts) print(dt.isoformat())
Convert for Display
from datetime import timezone
from zoneinfo import ZoneInfo
dt_utc = datetime.now(timezone.utc)
dt_tr = dt_utc.astimezone(ZoneInfo("Europe/Istanbul"))
print(dt_tr.isoformat())
Operational Checklist
- Store timestamps in UTC; convert only at the edges (UI/reporting).
- Never compare naive and aware datetimes.
- Use ISO 8601 for interchange and logs.
Failure Modes
- DST shifts: local time repeats or skips, breaking schedules.
- Naive timestamps: time math becomes ambiguous across regions.