Skip to content

Lesson 15 of 20 · 15m

Naive Datetimes Are Bugs

datetime.now() returns unlabeled local wall time — aware datetimes via ZoneInfo and UTC, epoch math, and monotonic clocks for durations.

datetime.now() returns your server's local wall-clock time with tzinfo=None — a naive datetime. The same call on a box in New York and a box in Frankfurt produces different instants labeled identically, and nothing in the type tells them apart. Store it, ship it across a region, and you have created a timestamp whose meaning depends on which machine happened to run the code. That is the bug the naive type encodes: it looks like a time and isn't one.

Naive vs aware

A datetime is aware iff it carries a tzinfo. Python protects you in exactly one place: comparing naive to aware raises TypeError. That crash is the feature. Everything else is silent — naive arithmetic proceeds, naive storage proceeds, and the wrongness lands weeks later in a report that ran twice or not at all.

datetime.now(UTC) — the datetime.UTC alias added in 3.11, equal to timezone.utc — is the call you meant. datetime.utcnow() was deprecated in 3.12: it returns a naive UTC datetime, the worst answer — right instant, unlabeled.

Zones are zoneinfo, not offsets

ZoneInfo("America/New_York") (PEP 615, 3.9+) carries the real rules — EST versus EDT, the two Sunday anomalies — where a fixed timedelta(hours=-5) is wrong half the year. Windows lacks the IANA database system-wide; the tzdata PyPI package fills it.

DST is where naive code dies. Spring forward: 2:00–2:59 a.m. does not exist — a scheduler set for 2:30 skips. Fall back: 1:00–1:59 happens twice; fold=0|1 on the aware datetime disambiguates. A nightly job keyed to local time double-runs or skips at least twice a year, silently both times.

dt + timedelta(days=1) on an aware datetime does wall math, not instant math: it lands on the same local clock reading a day later — 9:00 EST plus one day is 9:00 EDT, which across spring-forward is 23 real hours, not 24. For actual elapsed time, do the arithmetic in UTC — dt.astimezone(UTC) + timedelta(days=1) — and convert back. "Tomorrow at 9 a.m." and "86,400 seconds from now" are different questions; know which one you are answering.

The storage and parsing rules

  • Store UTC: epoch or ISO 8601 with offset. dt.isoformat() writes 2026-11-16T11:23:00-05:00 — self-describing, sortable, parseable.
  • datetime.fromisoformat handles Z since 3.11; before that dateutil.parser.isoparse was the answer.
  • Never persist bare datetime.now() — you saved an ambiguous instant.
  • dt.timestamp() on an aware datetime gives epoch. On a naive one it interprets the value in local time — one more silent, region-dependent answer.

Durations are a different clock entirely

time.time() is wall time: NTP slew, leap smears, an admin's date correction can move it backward. time.monotonic() only goes forward and exists for measuring elapsed time — timeouts, retries, rate limits. time.perf_counter() is the high-resolution sibling for benchmarks. Every deadline = time.time() + 30 carries a latent "the clock stepped and my timeout went negative" bug.

dt.astimezone(ZoneInfo("America/New_York")) converts an aware instant to another zone — same moment, different wall label. That is the correct move at the boundary: store UTC, convert at display time, never store the converted value back.

Parsing and testing

datetime.strptime(s, "%Y-%m-%d") parses known formats — the format codes are strftime's, and %z/%Z accept offsets and zone names. dateutil.parser.parse handles the formats you didn't predict, at the cost of guessing. For tests, freezegun (@freeze_time("2026-11-16")) or time-machine freeze datetime.now at a fixed instant — the standard answer to testing expiry, retries, and "runs at midnight" logic without sleeping the suite. A test that calls time.sleep(60) to watch a timeout is a test that gets deleted.

The rules

datetime.now(UTC) everywhere, ZoneInfo for the user's zone at display time, ISO-with-offset or epoch at rest, monotonic for durations. If a datetime has no tzinfo, it is not a time — it is a guess about which machine ran the code.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.