fromisoformat Parses Z Suffixes and ISO Week Dates

Parse UTC Z timestamps, compact dates, and ISO week strings via Python 3.11 datetime.fromisoformat, rejecting naive timestamps without tzinfo.

PythonForm Validation

Code

pythonsnippet
23 lines
from datetime import UTC, datetime

# Python 3.11+ accepts 'Z' UTC suffixes, compact ISO forms, and ISO week dates
samples = [
    "2026-11-24T09:15:30Z",
    "20261124T111530+0200",
    "2026-W48-2T09:15:30+00:00",
]

for raw in samples:
    parsed = datetime.fromisoformat(raw)
    print(f"{raw:27} -> UTC: {parsed.astimezone(UTC).isoformat()}")

def parse_aware_utc(raw: str) -> datetime:
    dt = datetime.fromisoformat(raw)
    if dt.tzinfo is None or dt.utcoffset() is None:
        raise ValueError(f"timezone offset required: {raw!r}")
    return dt.astimezone(UTC)

try:
    parse_aware_utc("2026-11-24T09:15:30")
except ValueError as exc:
    print("rejected naive:", exc)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

2026-11-24T09:15:30Z        -> UTC: 2026-11-24T09:15:30+00:00
20261124T111530+0200        -> UTC: 2026-11-24T09:15:30+00:00
2026-W48-2T09:15:30+00:00   -> UTC: 2026-11-24T09:15:30+00:00
rejected naive: timezone offset required: '2026-11-24T09:15:30'

Implementation trace — fromisoformat Parses Z Suffixes and ISO Week Dates

All processing steps sit cleanly inside the callable parse_aware_utc.

A single loop drives the file — for raw in samples. A guard precedes the ValueError: bad state stops the flow there instead of continuing.

What to watch for

  • The package manager never enters the picture for this snippet.
  • The guard dt.tzinfo is None or dt.utcoffset() is None halts further processing right away via an upfront raise when its condition holds.

Using it

Signature: def parse_aware_utc(raw: str) -> datetime

Output lines are prefixed (rejected naive:), giving each phase of execution its own readable output marker.

Import parse_aware_utc from the file and call it — the rest of the code is implementation detail.

Key statements

if dt.tzinfo is None or dt.utcoffset() is None:
    raise ValueError(f"timezone offset required: {raw!r}")
except ValueError as exc:
    print("rejected naive:", exc)

Interactive Tools for This Topic

FAQ

What does the snippet do with malformed data?
`ValueError` is raised at the guard (`dt.tzinfo is None or dt.utcoffset() is None`), so invalid state never reaches the main logic.
Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. Every import resolves inside the standard library — `datetime`. The file defines `parse_aware_utc` at load time.