Sub topic 12
Practical rules for real programs
This chapter assumes you know datetime, timedelta, ZoneInfo, and astimezone, and that you understand naive versus aware datetimes. It collects them into rules you can apply to real programs.
Rule 1: Keep time in UTC inside your program
Convert every timestamp to UTC when it enters your program. Store and compare it in UTC. Convert to a local zone only when you show it to a person.
UTC has no daylight saving changes, so there are no gaps or repeated hours to handle. Two UTC values always compare and subtract correctly.
Rule 2: Never create naive datetimes for real moments
A naive datetime does not say which moment it means. Always create aware values:
- Use
datetime.now(timezone.utc). - Avoid
datetime.utcnow(). It returns a naive value, and it is deprecated since Python 3.12. - Avoid
datetime.now()with no argument. It returns naive local time.
Python raises TypeError when you compare naive and aware values. Treat that error as useful, because it points at a bug in your data flow.
Rule 3: Validate at the boundary
Check input where it enters the program, not later. This helper rejects timestamps without an offset and normalizes the rest to UTC.
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
def parse_utc(text: str) -> datetime:
dt = datetime.fromisoformat(text)
if dt.utcoffset() is None:
raise ValueError(f"timestamp has no offset: {text!r}")
return dt.astimezone(timezone.utc)
def show_local(dt_utc: datetime, zone: str) -> str:
return dt_utc.astimezone(ZoneInfo(zone)).strftime("%Y-%m-%d %H:%M %Z")
stored = parse_utc("2026-11-26T14:00:00+00:00")
print(stored.isoformat())
print(show_local(stored, "Asia/Tokyo"))This prints 2026-11-26T14:00:00+00:00 and then 2026-11-26 23:00 JST.
fromisoformat accepts a trailing Z only from Python 3.11. On 3.9 and 3.10, normalize it first with text.replace("Z", "+00:00").
Rule 4: Store the zone name for future local events
UTC is right for things that already happened. A future appointment is different. "Every meeting is at 09:00 in Berlin" is a promise about wall-clock time. Governments can change daylight saving rules before the date arrives. If you convert to UTC today, the stored value may be wrong later.
For future events, store the local wall time and the IANA zone name (a name such as Europe/Berlin). Convert to UTC when you need the actual moment.
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
event = {"local": "2027-03-15T09:00:00", "zone": "Europe/Berlin"}
def event_utc(ev: dict) -> datetime:
naive = datetime.fromisoformat(ev["local"])
aware = naive.replace(tzinfo=ZoneInfo(ev["zone"]))
return aware.astimezone(timezone.utc)
print(event_utc(event))Berlin is on standard time (UTC+1) on that date, so this prints 2027-03-15 08:00:00+00:00.
Store the zone name, not an abbreviation like CET. Abbreviations are ambiguous and carry no rules. Do not store a fixed offset either, because the offset changes with daylight saving.
Rule 5: Pick the right kind of arithmetic
| You want | Do this | Why |
|---|---|---|
| Exactly 24 hours later | Convert to UTC, add `timedelta`, convert back | Elapsed time is not affected by clock changes |
| Same time tomorrow on the wall clock | Add `timedelta(days=1)` to the aware local value | The wall time stays the same across a daylight saving change |
| Time between two events | Subtract two aware values | Subtraction of values in the same zone ignores offset changes, so use UTC to be safe |
Always convert both values to UTC before you measure elapsed time. Local-zone subtraction can be off by an hour around a daylight saving change.
Rule 6: Handle ambiguous and missing local times on purpose
When a user types a local time, it can be repeated (fold) or skipped (gap). Python picks fold=0 by default and does not warn you. For scheduling and billing, decide a policy: ask the user, always take the first occurrence, or reject times in a gap.
Rule 7: Make zone data available
ZoneInfo reads the operating system's IANA database. Windows does not ship one, and some minimal containers do not either. Without it, ZoneInfo("Europe/Berlin") raises ZoneInfoNotFoundError. Add the tzdata package to your dependencies so the data is always present:
# requirements.txt
tzdataRule 8: Format with ISO 8601 when machines read the result
Use isoformat() for logs, APIs, and storage. Use strftime only for human display. A UTC value in ISO 8601 sorts correctly as text and parses back without loss.
Exercise
A user books a dentist appointment for 2027-06-10 at 15:00 in "America/Chicago". Which values should you store, and why not just store the UTC time?
Show answer
Store the local wall time "2027-06-10T15:00:00" and the zone name "America/Chicago". Convert to UTC only when you need the moment, for example to send a reminder. Rules for the zone can change before June 2027. A UTC value computed today would then point to the wrong wall-clock time, while the stored local time and zone name stay correct.