Parse ISO-8601 timestamps into UTC
Python
from datetime import datetime, timezone
def parse_utc(value: str) -> datetime:
"""Parse an ISO-8601 timestamp and normalise it to UTC."""
text = value.strip()
if text.endswith("Z"): # fromisoformat accepts Z only on Python 3.11+
text = text[:-1] + "+00:00"
parsed = datetime.fromisoformat(text)
if parsed.tzinfo is None: # treat naive input as UTC
return parsed.replace(tzinfo=timezone.utc)
return parsed.astimezone(timezone.utc)
def format_utc(value: str) -> str:
"""Render any accepted timestamp as a stable, sortable UTC string."""
return parse_utc(value).strftime("%Y-%m-%dT%H:%M:%SZ")
if __name__ == "__main__":
samples = ["2024-05-01T12:30:00+02:00", "2024-05-01T10:30:00Z", "2024-05-01 10:30:00"]
for sample in samples:
print(sample, "->", format_utc(sample))