Python Basics: Parsing Timestamps and Converting to UTC
Python’s standard-library datetime module parses timestamps, converts offsets, and calculates durations. These examples use Python 3.12 or newer on Linux. The saved scripts create no data files.
Parse a timestamp with an offset
Save as demo_datetime_1.py:
from datetime import datetime, timezone
meeting = datetime.fromisoformat("2026-10-11T09:30:00+09:00")
meeting_utc = meeting.astimezone(timezone.utc)
print(meeting.isoformat())
print(meeting_utc.isoformat())
print(meeting == meeting_utc)Run:
python3 demo_datetime_1.pyOutput:
2026-10-11T09:30:00+09:00
2026-10-11T00:30:00+00:00
TrueThe offset makes this an aware datetime. Both representations identify the same instant. astimezone() converts the clock time; replacing tzinfo would only relabel it.
Add time and measure a duration
Save as demo_datetime_2.py:
from datetime import datetime, timedelta
started = datetime.fromisoformat("2026-10-11T23:45:00+00:00")
finished = started + timedelta(minutes=90)
print(finished.isoformat())
print((finished - started).total_seconds())Run:
python3 demo_datetime_2.pyOutput:
2026-10-12T01:15:00+00:00
5400.0timedelta crosses the date boundary automatically. Use total_seconds() for the full duration; .seconds contains only the seconds remaining after whole days.
Reject timestamps without an offset
Without an offset, fromisoformat() produces a naive datetime. Parsing does not assume UTC. Check that requirement explicitly:
Save as demo_datetime_3.py:
from datetime import datetime
for timestamp in ["2026-10-11T09:30:00", "not-a-date"]:
try:
parsed = datetime.fromisoformat(timestamp)
if parsed.utcoffset() is None:
raise ValueError("offset required")
except ValueError:
print("Expected a valid timestamp with an offset")Run:
python3 demo_datetime_3.pyOutput:
Expected a valid timestamp with an offset
Expected a valid timestamp with an offsetFixed offsets do not describe regional daylight-saving rules. Use zoneinfo for named regions. For elapsed-time calculations across clock changes, convert both endpoints to UTC before subtracting.
Reference
Acknowledgements
This post was created with assistance from AI.