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.
Code
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 Nonehalts further processing right away via an upfrontraisewhen 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
ISO Week CalculatorFind the ISO 8601 week number, ISO week-year, week start and end dates, and day of year for any calendar date, with strict date validation.JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.