On this page
datetime
Prev: dataclasses | Up: stdlib_module | Next: dbm
Rel: zoneinfo, calendar, collections, heapq, bisect
Ref: docs.python.org — datetime
Tags: #public #python3 #stdlib
Import
import datetime
Overview
Immutable date, time, timestamp, and duration types (date, time, datetime, timedelta, timezone, UTC). Always store and compute timestamps as timezone-aware UTC (datetime.now(UTC)) and convert to IANA local timezones with zoneinfo only at display boundaries; use time.perf_counter() from time for benchmarking elapsed durations.
Quick Start
from datetime import UTC, datetime, timedelta
now = datetime.now(UTC)
deadline = now + timedelta(days=7, hours=2)
iso = now.isoformat()
parsed = datetime.fromisoformat(iso)
assert parsed == now and deadline > now
Implementation Walkthrough
1. Timezone-Aware Conversions with zoneinfo
from datetime import UTC, datetime
from zoneinfo import ZoneInfo
utc_dt = datetime(2026, 12, 1, 18, 0, tzinfo=UTC)
vegas = utc_dt.astimezone(ZoneInfo("America/Los_Angeles"))
assert vegas.strftime("%Y-%m-%d %H:%M %Z") == "2026-12-01 10:00 PST"
2. Parsing ISO 8601 Strings & Computing Date Differences
In Python 3.11+, datetime.fromisoformat() handles trailing "Z" UTC markers natively:
from datetime import date, datetime
ts = datetime.fromisoformat("2026-12-01T15:30:00Z")
days_left = (date(2027, 1, 1) - ts.date()).days
assert days_left == 31
Gotchas & Boundaries
- Never use
datetime.utcnow()ordatetime.utcfromtimestamp(): Both are deprecated because they return naive datetimes; usedatetime.now(UTC)anddatetime.fromtimestamp(ts, UTC). - Naive and aware datetimes cannot be compared or subtracted: Mixing them raises
TypeError; normalize to UTC at ingress. timedeltahas nomonthsoryears: Calendar months vary in length; handle month arithmetic explicitly or normalize to days.- Wall-clock time can jump backward (NTP/DST): Use
time.monotonic()ortime.perf_counter()to measure timeouts and elapsed execution time.
Classes & Objects
- datetime.date — date(year, month, day) --> date object (Methods:
.ctime(),.fromisocalendar(),.fromisoformat(),.fromordinal(),.fromtimestamp(),.isocalendar()) - datetime.datetime — The year, month and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints. (Methods:
.astimezone(),.combine(),.ctime(),.date(),.dst(),.fromisocalendar()) - datetime.time — All arguments are optional. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints. (Methods:
.dst(),.fromisoformat(),.isoformat(),.replace(),.strftime(),.strptime()) - datetime.timedelta — Difference between two datetime values. (Methods:
.total_seconds()) - datetime.timezone — Fixed offset from UTC implementation of tzinfo. (Methods:
.dst(),.fromutc(),.tzname(),.utcoffset()) - datetime.tzinfo — Abstract base class for time zone info objects. (Methods:
.dst(),.fromutc(),.tzname(),.utcoffset())
Constants & Attributes
datetime.MAXYEAR(int) =9999datetime.MINYEAR(int) =1datetime.UTC(timezone) =datetime.timezone.utc
Linked from
- tuts/python3
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/array
- tuts/python3/stdlib_module/bisect
- tuts/python3/stdlib_module/calendar
- tuts/python3/stdlib_module/collections
- tuts/python3/stdlib_module/copy
- tuts/python3/stdlib_module/dataclasses
- tuts/python3/stdlib_module/dbm
- tuts/python3/stdlib_module/enum
- tuts/python3/stdlib_module/graphlib
- tuts/python3/stdlib_module/heapq
- tuts/python3/stdlib_module/pprint
- tuts/python3/stdlib_module/reprlib
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/time
- tuts/python3/stdlib_module/types
- tuts/python3/stdlib_module/weakref
- tuts/python3/stdlib_module/zoneinfo
Related notes
- tuts/python3/stdlib_module/bisect Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/calendar Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/collections Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/dataclasses Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/dbm Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/heapq Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/time Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/zoneinfo Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib