Lesson 34 of 52Python power tools
Dates, Times and Time Zones
Store time in UTC, convert at the edges with zoneinfo, survive daylight saving changes, and parse, format and test time-based code safely.
A reminder email goes out an hour early for every customer in London, but only for one week in spring. A daily report counts "orders today" and is short by everything placed after 7 p.m. in New York. A subscription renews twice on the night the clocks go back. None of these are exotic. They are the most common time bugs in production code, and they all come from the same few mistakes. This lesson gives you the rules that prevent them and the details you need when the rules are not enough.
Four types and one big split
The datetime module has four types you use every day:
date: a calendar day,date(2026, 10, 22). No time, no zone.time: a time of day,time(14, 30). Rarely useful on its own.datetime: a date plus a time, optionally with a time zone.timedelta: a duration, such astimedelta(days=1, hours=3).
The split that matters is inside datetime. A naive datetime has no tzinfo. It says "14:30 on 22 October" without saying where, so it does not identify a single moment. An aware datetime carries a tzinfo and therefore an offset from UTC, so it names exactly one instant on the planet.
Python refuses to order or subtract one kind against the other, because the answer would be a guess.
Press Run (⌘ Enter) to see what happens.The last line is a quiet trap. == between naive and aware does not raise, it just returns False. So a lookup like if event.starts_at == cutoff can silently never match. If a codebase mixes the two, fix that first: pick aware everywhere.
The rule: UTC inside, local at the edges
Every working system follows the same pattern. Store and compute in UTC. Convert to a local zone only at the edges: when you show a time to a person, and when you read a time a person typed.
A person types a wall-clock time. On its own it is ambiguous, so the edge attaches the user's zone (America/New_York) and converts to UTC straight away.
Get "now" with datetime.now(UTC). The UTC constant has existed since Python 3.11 (it is the same object as timezone.utc).
Do not use datetime.utcnow() or datetime.utcfromtimestamp(). They have been deprecated since 3.12 because they return naive values holding UTC numbers. The object looks like a UTC time but does not know it, and the next method you call treats it as local time. For example, datetime.utcnow().timestamp() interprets the value in the machine's local zone, so on a server set to anything other than UTC you get a Unix timestamp that is off by hours. You will still meet these calls in older code. Replace them on sight.
Time zones with zoneinfo
An offset like +01:00 is not a time zone. London is +00:00 in winter and +01:00 in summer. A zone is a named set of rules, such as Europe/London, from the IANA time zone database. That database changes several times a year as governments change their rules, so you always want the zone name, never a hard-coded offset, for anything a person schedules.
Since Python 3.9 the standard library has zoneinfo.ZoneInfo. On macOS and Linux it reads the operating system's zone files. Windows has no such files, so you install the tzdata package from PyPI and zoneinfo finds it automatically. The browser Python on this site is in the same position as Windows, which is why the examples below import tzdata first.
Press Run (⌘ Enter) to see what happens.astimezone(zone) converts an aware datetime to the same instant in another zone. The instant does not change, only how it is written. Passing tzinfo=ZoneInfo(...) to the constructor is different: it says "these wall-clock numbers are local to this zone", which is how you build a time from user input.
Reading old code: the pytz localize trap
Before zoneinfo, everyone used the third-party pytz. Do not add it to new code, but you will read it. Its zones only work through tz.localize(naive_dt). If you write datetime(2026, 7, 1, 9, 0, tzinfo=pytz.timezone("America/New_York")), pytz attaches the zone's oldest entry, local mean time, and you get an offset of -04:56. That bug survives code review because the result looks almost right. When you migrate, replace tz.localize(dt) with dt.replace(tzinfo=ZoneInfo(name)) and drop the tz.normalize(...) calls, since zoneinfo handles daylight saving changes itself.
Daylight saving: gaps, folds and "one day later"
Twice a year local time misbehaves. In London on 29 March 2026 the clocks jump from 01:00 to 02:00, so 01:30 never happens: it falls in a gap. On 25 October 2026 they go from 02:00 back to 01:00, so 01:30 happens twice: it is ambiguous.
Python resolves this with the fold attribute. fold=0 means the first occurrence of an ambiguous time, fold=1 the second. For a time in a gap, zoneinfo does not raise. It gives you a time that does not exist on any clock, so validate user input around transitions if it matters.
The subtler trap is arithmetic. When both sides of a calculation use the same tzinfo object, Python does wall-clock arithmetic and ignores the offset. ZoneInfo("Europe/London") is cached, so two calls return the same object, and this applies far more often than people expect.
Press Run (⌘ Enter) to see what happens.Read the output closely. Adding timedelta(days=1) and timedelta(hours=24) give the same result in a zone, because both mean "move the wall clock". Python then reports 24 hours elapsed when only 23 really passed. And the two different 01:30s compare equal, although they are an hour apart.
Which one is correct depends on the product question. "Remind me at 9 a.m. every day" is wall-clock time: it must stay at 9 a.m. after the change. "The session expires in 24 hours" is elapsed time: do that sum in UTC. Seniors ask which one a requirement means before writing the code.
What does this print?
from datetime import datetime, timedelta, UTC
from zoneinfo import ZoneInfo
ny = ZoneInfo("America/New_York")
start = datetime(2026, 11, 1, 0, 0, tzinfo=ny)
end = start + timedelta(days=1)
print(end.hour, end.astimezone(UTC) - start.astimezone(UTC))Scheduling future events
For a past event, a UTC instant is the complete truth. For a future event that a person scheduled in local time, store the wall-clock time and the zone name, such as 2027-04-02 09:00 plus Europe/Berlin, and compute the UTC instant when you need it. If you convert to UTC at booking time and the country changes its rules before then, your stored instant points to the wrong hour. It sounds rare, but rule changes happen most years somewhere. Recurring events need this approach for the same reason: each occurrence is "9:00 local", not "every 86,400 seconds".
Parsing and formatting
Machines should exchange times as ISO 8601 strings with an offset: 2026-10-22T14:05:00+00:00 or 2026-10-22T14:05:00Z. isoformat() writes them and datetime.fromisoformat() reads them. Since 3.11, fromisoformat accepts most of ISO 8601, including the Z suffix that JavaScript's toISOString() produces.
For human formats, strftime formats and strptime parses, using codes such as these:
| Code | Meaning | Example |
|---|---|---|
%Y-%m-%d | year, month, day | 2026-10-22 |
%H:%M:%S | 24-hour time | 14:05:00 |
%d %b %Y | day, short month name, year | 22 Oct 2026 |
%a / %A | weekday name, short / full | Thu / Thursday |
%z | offset | +0100 |
%Z | zone abbreviation (display only) | BST |
Month and weekday names follow the process locale, so do not rely on %b when parsing machine data. And strptime returns a naive datetime unless the input contains an offset and you parse it with %z. Attach the zone right after parsing.
Press Run (⌘ Enter) to see what happens.Unix timestamps
A Unix timestamp counts seconds since 1970-01-01 00:00 UTC. It has no zone because it is already an instant. Convert with dt.timestamp() and datetime.fromtimestamp(ts, UTC). Always pass the zone: without it, fromtimestamp returns naive local time.
The classic bug at the boundary with JavaScript is units. Date.now() in JavaScript returns milliseconds. Python uses seconds, often as a float. Feed milliseconds to Python and you get a ValueError, because the year lands past 9999. The reverse mistake, seconds read as milliseconds, puts every event in January 1970. Name your fields created_at_ms or created_at_s so the unit is in the contract.
Press Run (⌘ Enter) to see what happens.Measuring durations
Never time code with datetime.now() or time.time(). The wall clock can jump: NTP corrects drift, an admin changes the time, a VM resumes. A duration measured across a jump can be negative. Use time.monotonic() for timeouts and elapsed time, and time.perf_counter() for benchmarking, which has the highest resolution available. Both only make sense as differences between two readings; their absolute values mean nothing.
import time
start = time.perf_counter()
run_report()
elapsed = time.perf_counter() - start
print(f"report took {elapsed:.3f}s")Testing code that reads the clock
A function that calls datetime.now(UTC) inside itself is hard to test: the answer changes every run, and you cannot reach the DST night or the last day of February on demand. The clean fix is to inject the clock. Pass now in as a parameter, or pass a function that returns it, with the real clock as the default.
Press Run (⌘ Enter) to see what happens.When you cannot change the signature, for example in old code or third-party calls, freeze time from the test. The third-party libraries time-machine and freezegun patch the clock for the duration of a test. time-machine is the faster and more thorough of the two; check each project's docs for the current API. Either way, write explicit tests for the edges: a DST change in each direction, 29 February, midnight, and the end of a month.
Databases and APIs
In PostgreSQL use timestamptz ("timestamp with time zone") for instants. Despite its name it does not store a zone: it converts input to UTC and stores that, then converts to the session's zone on output. Plain timestamp stores the numbers you give it and forgets the offset, the database version of a naive datetime. Most Python drivers return aware datetimes for timestamptz columns. Use a plain date column for things that are genuinely days, like a birthday or an invoice date, where converting zones would shift the day.
In JSON there is no date type. Send ISO 8601 strings with an explicit offset or Z, and reject inputs without one at the API edge rather than guessing. json.dumps cannot serialise a datetime, which is a good thing: it forces you to choose the format on purpose.
Match each task to the right tool.
datetime.utcnow()?Put the steps for handling a time a user typed into a form in order.
- Tap the steps below in the right order.
- naive datetime
- A datetime with no tzinfo. It does not identify a single moment and cannot be compared with aware values.
- aware datetime
- A datetime with a tzinfo, so it has a UTC offset and names exactly one instant.
- IANA zone
- A named set of time rules such as Europe/London, from the tz database that zoneinfo reads.
- UTC offset
- The difference from UTC at one moment, like +01:00. A zone's offset changes over the year.
- fold
- The datetime attribute that picks the first (0) or second (1) occurrence of an ambiguous local time.
- timestamptz
- The Postgres type for instants. It stores UTC and converts to the session zone on output.
- monotonic clock
- A clock that never goes backwards, used for durations and timeouts instead of wall time.