Sub topic 12
Practical rules for real programs
This chapter gathers the earlier material into rules you can apply to a codebase. It assumes you know the datetime, timedelta, and ZoneInfo basics, the difference between naive and aware datetimes, and how fold marks repeated local times. It also assumes Python 3.9 or later. A few details differ in 3.11 and later, and the text says where.
Rule 1: Use aware datetimes inside your program
A naive datetime does not say which moment it names. datetime(2026, 11, 26, 9, 0) could be 9:00 in New York or 9:00 in Tokyo. Python will not compare a naive and an aware value, and it raises TypeError when you try. That error is useful, because it exposes the ambiguity early.
The practical rule is that every datetime your program passes around, stores, or compares should be aware. Naive values should exist only briefly, at the moment you attach a zone to them.
Two older APIs return naive values that represent UTC, which makes them easy to misuse:
datetime.utcnow()is deprecated as of Python 3.12.datetime.utcfromtimestamp()is deprecated as of Python 3.12.
Use these instead:
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
moment = datetime.fromtimestamp(1_700_000_000, tz=timezone.utc)
print(now.tzinfo, moment.isoformat())The second line prints 2023-11-14T22:13:20+00:00.
Rule 2: Store UTC, convert only for display
UTC has no daylight saving changes, so UTC values never repeat and never skip. Sorting, comparing, and subtracting them give correct answers. Convert to a local zone at the last step, when you show the value to a person.
The diagram below shows where each conversion belongs.
A small boundary helper enforces the rule. It parses ISO 8601 text, rejects values with no offset, and normalizes to UTC:
from datetime import datetime, timezone
def parse_utc(text: str) -> datetime:
dt = datetime.fromisoformat(text)
if dt.utcoffset() is None:
raise ValueError(f"timestamp has no UTC offset: {text!r}")
return dt.astimezone(timezone.utc)
print(parse_utc("2026-11-26T09:00:00-05:00").isoformat())
try:
parse_utc("2026-11-26T09:00:00")
except ValueError as e:
print(e)The first call prints 2026-11-26T14:00:00+00:00. The second raises, and the handler prints timestamp has no UTC offset: '2026-11-26T09:00:00'.
The check uses utcoffset() is None instead of tzinfo is None. An object can have a tzinfo attribute and still return None from utcoffset(), and in that case it is still naive by the definition in the documentation.
Rule 3: Do not guess a zone for naive input
When naive input arrives, you have two honest choices. Reject it, or attach a zone that you know is correct and document that assumption. A form field that says "meeting time" with no zone is a case where you must know the user's zone from somewhere else, such as their profile.
Attach a zone with replace(tzinfo=...), not astimezone(). Called on a naive value, astimezone() assumes the machine's local zone. That makes results depend on where the code runs.
from datetime import datetime
from zoneinfo import ZoneInfo
naive = datetime(2026, 11, 26, 9, 0)
aware = naive.replace(tzinfo=ZoneInfo("America/New_York"))
print(aware.isoformat())This prints 2026-11-26T09:00:00-05:00.
Rule 4: For future events, store local time and the zone name
Rule 2 has one exception. Consider a recurring meeting set for 9:00 in New York next March. If you convert it to UTC today and store that, you have frozen today's idea of the offset. Governments change daylight saving rules, and the IANA database (the shared time zone database) is updated to match. A stored UTC value cannot follow such a change. A stored local time plus a zone name can.
For events that are defined by a local clock, store three things:
- the local wall-clock time, without an offset
- the IANA key, such as
America/New_York - optionally, the UTC value you computed, as a cache
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
stored_local = "2027-03-15T09:00:00"
stored_zone = "America/New_York"
event = datetime.fromisoformat(stored_local).replace(tzinfo=ZoneInfo(stored_zone))
print(event.astimezone(timezone.utc).isoformat())Under current US rules this prints 2027-03-15T13:00:00+00:00, because daylight saving time begins on March 14, 2027. If the rules change and your tzdata is updated, the same stored fields give the new correct UTC time with no migration.
Past events are different. A log entry or a payment happened at one absolute moment, so UTC is the right record.
| Kind of value | What to store | Why |
|---|---|---|
| Something that already happened | Aware UTC datetime or UTC timestamp | One absolute moment, no ambiguity |
| Future event tied to a local clock | Local time plus IANA zone key | Survives rule changes and DST |
| Future event at an absolute instant | Aware UTC datetime | Fixed moment, such as a rocket launch |
| A date with no time of day | `date` object | A birthday has no zone |
Rule 5: Pick the arithmetic that matches the question
Adding a timedelta to an aware datetime works on the wall clock and keeps the zone. Across a daylight saving change, that differs from adding real elapsed time. The earlier chapter on DST arithmetic showed this for addition. The same trap exists for subtraction, and it is easy to miss.
When both operands share the same tzinfo object, Python subtracts the naive wall-clock values and ignores offsets:
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
tz = ZoneInfo("America/New_York")
start = datetime(2026, 3, 7, 12, 0, tzinfo=tz)
end = datetime(2026, 3, 8, 12, 0, tzinfo=tz)
print(end - start)
print(end.astimezone(timezone.utc) - start.astimezone(timezone.utc))The first line prints 1 day, 0:00:00 and the second prints 23:00:00. Clocks jumped forward on March 8, so only 23 hours passed. If a billing or timeout calculation needs elapsed time, convert both values to UTC first.
Use this decision rule:
- Use wall-clock arithmetic for questions about the calendar, such as "same time tomorrow" or "first of next month at 09:00".
- Use UTC arithmetic for questions about elapsed time, such as timeouts, durations, and rate limits.
For measuring how long code takes to run, use neither. Use time.monotonic() or time.perf_counter(), which do not move when the system clock is adjusted.
Rule 6: Handle gaps and folds on purpose
Two kinds of local time need care when you build a datetime from user input:
- A gap is a local time that never happened, such as 02:30 on 2026-03-08 in New York.
- A fold is a local time that happened twice, such as 01:30 on 2026-11-01 in New York.
Python does not raise an error for either. For a gap, it accepts the value and gives it an offset that makes the result look odd. For a fold, it picks the first occurrence unless you set fold=1. If your program accepts local times from users, validate them with a round trip through UTC:
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
def exists(local: datetime) -> bool:
"""True if this aware local time survives a UTC round trip."""
round_trip = local.astimezone(timezone.utc).astimezone(local.tzinfo)
return round_trip.replace(tzinfo=None) == local.replace(tzinfo=None)
tz = ZoneInfo("America/New_York")
print(exists(datetime(2026, 3, 8, 2, 30, tzinfo=tz)))
print(exists(datetime(2026, 3, 8, 3, 30, tzinfo=tz)))This prints False, then True. The first time was skipped, so the round trip shifts it to 03:30.
For folds, decide a policy and write it down. Common choices are to take the first occurrence, which is Python's default, or to ask the user which one they meant. Whichever you choose, apply it everywhere.
Rule 7: Serialize as ISO 8601 with an offset
When you exchange datetimes through JSON, databases, or logs, use ISO 8601 text with an explicit offset, produced by isoformat(). It sorts correctly as text when all values share one offset. Every mainstream language can read it.
A few details matter in practice:
fromisoformat()accepts only a limited set of formats in Python 3.9 and 3.10. In particular, it does not accept a trailingZ. Python 3.11 and later acceptZand most ISO 8601 variants.strptime()with%zacceptsZin all supported versions.- Do not store
strftime()output meant for people, such as"%A, %d %B", as your data format. Names depend on the locale, and the output carries no offset.
If you must support 3.9 or 3.10 and receive Z, normalize the text first:
from datetime import datetime
text = "2026-11-26T11:07:59Z"
dt = datetime.fromisoformat(text.replace("Z", "+00:00"))
print(dt.isoformat())This prints 2026-11-26T11:07:59+00:00.
For numbers, a POSIX timestamp is the number of seconds since 1970-01-01 00:00:00 UTC. It is zone-free by definition, so it is safe to store. Convert it back with an explicit tz, as in Rule 1. Know whether your source gives seconds or milliseconds before you convert. Dividing by 1000 is a common fix.
Rule 8: Make zone data a checked dependency
ZoneInfo reads the IANA database from the operating system when it can. Windows has no such database, and minimal container images often lack one. In those environments, ZoneInfo("America/New_York") raises ZoneInfoNotFoundError unless the tzdata package is installed.
Add tzdata to your dependencies when your program runs on Windows or in slim containers. Then convert lookup errors into messages a user can act on:
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
def load_zone(key: str) -> ZoneInfo:
try:
return ZoneInfo(key)
except (ZoneInfoNotFoundError, ValueError) as e:
raise ValueError(f"unknown time zone: {key!r}") from e
print(load_zone("Asia/Tokyo"))
try:
load_zone("Mars/Olympus_Mons")
except ValueError as e:
print(e)This prints Asia/Tokyo, then unknown time zone: 'Mars/Olympus_Mons'. The ValueError in the except clause also covers malformed keys, which ZoneInfo rejects with that exception.
Zone rules change a few times a year. Keep the system data or the tzdata package current, as you would any other dependency.
Rule 9: Keep the clock replaceable
Code that calls datetime.now() deep inside a function is hard to test, because the result changes every run. Pass the current time in as an argument, with a default for production use:
from datetime import datetime, timedelta, timezone
def is_expired(expires_at: datetime, now: datetime | None = None) -> bool:
if now is None:
now = datetime.now(timezone.utc)
return expires_at <= now
issued = datetime(2026, 11, 26, 12, 0, tzinfo=timezone.utc)
expires = issued + timedelta(hours=1)
print(is_expired(expires, now=issued + timedelta(minutes=59)))
print(is_expired(expires, now=issued + timedelta(minutes=60)))This prints False, then True. The datetime | None annotation needs Python 3.10 or later. On 3.9, write Optional[datetime] from typing.
Tests can now cover the hour before a DST change, the repeated hour, and the skipped hour without waiting for them to occur.
A checklist
Review a codebase against these questions:
- Does any code call
utcnow(),utcfromtimestamp(), ordatetime.now()without an argument? - Is every parsed input checked for an offset or given a known zone?
- Is stored data UTC, except for future local-clock events, which keep a zone key?
- Is elapsed time computed from UTC values or from a monotonic clock?
- Is
tzdatalisted as a dependency where the operating system does not provide it? - Are gaps and folds handled for any local time that users type in?
Exercises
Exercise
A user in Berlin schedules a weekly reminder for 08:00 local time, starting next year. Your teammate proposes converting the first occurrence to UTC and storing only that value. What goes wrong, and what should you store instead?
Show answer
A single UTC value fixes today's offset. Berlin's offset changes with daylight saving time, and the rules themselves can change, so the reminder would drift to 07:00 or 09:00 local time for part of the year. Store the local time (08:00), the weekly recurrence, and the zone key Europe/Berlin. Build each occurrence as an aware datetime with ZoneInfo("Europe/Berlin") and convert it to UTC only when you need to schedule it.
Exercise
A New York datetime a is 2026-11-01 00:30 and b is 2026-11-01 03:30, both built with the same ZoneInfo("America/New_York") object. Without running code, what does b - a return, and what is the true elapsed time? How do you get the true value?
Show answer
b - a returns 3 hours, because both values share one tzinfo object and Python subtracts the wall-clock times. The true elapsed time is 4 hours, since clocks went back at 02:00 and the 01:00 hour happened twice. Convert both values with astimezone(timezone.utc) before subtracting to get 4:00:00.