Standard Library
Dates and Times
The datetime module separates calendar dates, clock times, combined datetimes, and durations. Import the types you need explicitly.
Use date for a calendar day and time for a time of day. Combine them into a timezone-aware datetime when you mean an instant.
isoformat() produces stable machine-readable text. It is a good default for examples, APIs, and logs.
Source
from datetime import date, datetime, time, timedelta, timezone
release_day = date(2026, 5, 4)
meeting_time = time(12, 30)
created_at = datetime.combine(release_day, meeting_time, tzinfo=timezone.utc)
print(release_day.isoformat())
print(meeting_time.isoformat())
print(created_at.isoformat())Output
2026-05-04
12:30:00
2026-05-04T12:30:00+00:00Use timedelta for durations. Adding one to a datetime produces another datetime without manually changing calendar fields.
Source
expires_at = created_at + timedelta(days=7, hours=2)
print(expires_at.isoformat())Output
2026-05-11T14:30:00+00:00Use strftime() for human-facing formatting and fromisoformat() when reading ISO 8601 text back into a datetime.
Source
print(created_at.strftime("%Y-%m-%d %H:%M %Z"))
iso_text = "2026-05-04T12:30:00+00:00"
parsed = datetime.fromisoformat(iso_text)
print(parsed == created_at)Output
2026-05-04 12:30 UTC
TrueNotes
- Use timezone-aware datetimes for instants that cross system or user boundaries.
- Use
datefor calendar days,timefor clock times,datetimefor both, andtimedeltafor durations. - Prefer ISO 8601 strings for interchange; use
strftimefor human-facing display.
See also
- prerequisite: String Formatting
- related: JSON
- related: Number Parsing
Run the complete example
Expected output
2026-05-04
12:30:00
2026-05-04T12:30:00+00:00
2026-05-11T14:30:00+00:00
2026-05-04 12:30 UTC
True
Execution time appears here after you run the example.