Standard Library

Dates and Times

datetime represents dates, times, durations, formatting, and parsing.

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:00
one instant−5h+0h
An aware datetime carries a UTC offset; one instant in time reads differently on two clocks.

Use 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:00

Use 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
True

Notes

See also

Run the complete example

Example code

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.