Datetime, Timezones (zoneinfo) & ISO 8601
Handling dates, times, leap years, and daylight saving shifts is one of the most bug-prone areas of software engineering. Learn how Python’s datetime module structures temporal objects, why naive datetimes are dangerous in production, how to leverage modernzoneinfo (PEP 615), and how to execute precise timedelta arithmetic.
1. The Core Temporal Classes
The standard datetime module exposes four primary classes:
date: Calendar date (year, month, day).time: Time of day independent of date (hour, minute, second, microsecond).datetime: Combination of date and time.timedelta: A duration expressing the exact difference between two dates or times.
from datetime import datetime, date, timedelta
# Create specific date and time
launch_date = datetime(2026, 12, 1, 9, 30, 0)
print("Launch Day of Week:", launch_date.strftime("%A")) # Tuesday
# Timedelta Arithmetic (Add 14 days and 6 hours)
maintenance_window = launch_date + timedelta(days=14, hours=6)
print("Maintenance Scheduled:", maintenance_window)2. Naive vs Aware Datetimes: Modern Timezones with zoneinfo
A naive datetime holds no timezone context (e.g., "2026-10-15 14:00"—in what city?). An aware datetime explicitly tracks its UTC offset and daylight saving status using zoneinfo.ZoneInfo:
TypeError: can't compare offset-naive and offset-aware datetimes! Always store timestamps in UTC.from datetime import datetime, timezone
from zoneinfo import ZoneInfo
# 1. ALWAYS create current timestamps in UTC
utc_now = datetime.now(timezone.utc)
print("UTC Timestamp:", utc_now.isoformat())
# 2. Convert UTC to local regional timezones cleanly
tokyo_time = utc_now.astimezone(ZoneInfo("Asia/Tokyo"))
ny_time = utc_now.astimezone(ZoneInfo("America/New_York"))
delhi_time = utc_now.astimezone(ZoneInfo("Asia/Kolkata"))
print("Tokyo Local:", tokyo_time.strftime("%Y-%m-%d %H:%M:%S %Z"))
print("New York Local:", ny_time.strftime("%Y-%m-%d %H:%M:%S %Z"))
print("New Delhi Local:", delhi_time.strftime("%Y-%m-%d %H:%M:%S %Z"))3. High-Performance ISO 8601 & Formatting
Modern web APIs exchange timestamps adhering to the ISO 8601 standard (e.g. 2026-10-15T14:30:00Z). Python provides optimized C-level parsing with fromisoformat():
# Parsing ISO 8601 strings directly (Fast & Robust)
raw_api_string = "2026-10-15T18:45:30.125000+00:00"
parsed_dt = datetime.fromisoformat(raw_api_string)
# Calculate elapsed time since API event
elapsed = datetime.now(timezone.utc) - parsed_dt
print(f"Elapsed time: {elapsed.total_seconds():.1f} seconds ago")
# Custom String Formatting with strftime
formatted = parsed_dt.strftime("%d %B %Y at %I:%M %p")
print("Readable Display:", formatted)Explore Related Tools
Hand-picked utilities and calculators related to this tool.
