Skip to content

Lesson 4 of 14 · 18m

Timestamps are hostile: formats, zones, and the naive-datetime trap

Normalize syslog, epoch, RFC 2822, and ISO timestamps to aware UTC before you compare anything.

The incident review asks one question: "what happened within ten minutes of the alert?" The evidence gives you four answers in four formats — syslog says Oct 1 03:12:47, the SIEM export carries 1759462367, the RSS feed gives Mon, 01 Oct 2026 03:00:00 GMT, and the API returns 2026-10-01T03:00:00Z. Timestamps are the most quietly-wrong data type in security tooling, and the bugs don't crash — they shift events across time.

The wrong model: a timestamp is a sortable string

It isn't, even when it looks like one. Oct 1 carries no year and no zone. 1759462367 could be seconds or milliseconds — divide wrong and your event lands in 1970 or in 55000 A.D., and nothing crashes because both are valid integers. Even clean ISO 8601 sorts wrong as text once offsets mix: 2026-10-01T03:00:00-05:00 is a later instant than 2026-10-01T04:00:00Z — the -05:00 offset puts it at 08:00Z — and lexicographic order says the opposite.

The fix is one rule: normalize to an aware UTC datetime at the boundary, compare datetimes, emit ISO. Everything else is a parser problem, and the stdlib covers it.

Parse each format with the right tool

from datetime import datetime, timezone
from email.utils import parsedate_to_datetime

# ISO 8601 — fromisoformat is strict about offsets on old Pythons
ts = datetime.fromisoformat("2026-10-01T03:00:00+00:00")

# Python < 3.11 rejects a trailing "Z" — normalize it yourself
ts = datetime.fromisoformat("2026-10-01T03:00:00Z".replace("Z", "+00:00"))

# RFC 2822 (RSS pubDate) — never strptime this, offsets vary wildly
ts = parsedate_to_datetime("Mon, 01 Oct 2026 03:00:00 GMT")

# Epoch — check magnitude before deciding the unit
def from_epoch(n):
    if n > 10_000_000_000:      # past ~year 2286 in seconds → it's millis
        n = n / 1000
    return datetime.fromtimestamp(n, tz=timezone.utc)

fromisoformat only learned to accept Z in Python 3.11 — on 3.10 and earlier it raises ValueError, which is exactly why so much production code does the .replace("Z", "+00:00") dance. For local times, zoneinfo.ZoneInfo("America/New_York") is the stdlib answer since Python 3.9 (PEP 615); pytz's localize() API is a known footgun — assigning tzinfo=pytz.timezone("US/Eastern") to a datetime gives you a fictional timezone off by several minutes, not an error.

Naive vs aware: the exception that's a gift

now = datetime.now()                      # naive — no zone attached
alert = parsedate_to_datetime("Mon, 01 Oct 2026 03:00:00 GMT")  # aware
delta = alert - now                       # TypeError

The TypeError: can't subtract offset-naive and offset-aware datetimes is loud and therefore merciful — it forces you to decide. The silent version is worse: two naive datetimes from different sources subtract happily and return a timedelta that's wrong by your UTC offset. Every event slides five hours east and nobody notices until a correlation fails.

now = datetime.now(timezone.utc)          # aware, always

Use datetime.now(timezone.utc) everywhere and astimezone() to convert for display. Store UTC ISO strings in state files and databases; epoch seconds if you must, but document the unit — the epoch-millis confusion has corrupted more analytics than any other timestamp bug.

Try this

Write when.py that accepts a timestamp in any of the four formats above (detect by shape), returns an aware UTC datetime, and prints both the UTC instant and its America/New_York rendering. Feed it Oct 1 03:12:47 — make it refuse politely rather than invent a year.

Field notes

  • Syslog has no year. For anything older than the current year, use journalctl -u <unit> -o json (real timestamps) or accept the ambiguity.
  • time.time() is aware-free — it's epoch seconds, no zone involved. The zone bugs live in datetime, not time.
  • The bug that ships: datetime.utcnow() — naive-UTC, deprecated since Python 3.12, and it produces the silent-naive-comparison class. datetime.now(timezone.utc) replaces it exactly.
  • Expiry math (cert validity, token TTL, expires_in) is always instant-vs-instant: keep both sides aware and the arithmetic is trivial.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.