datetime — dates and times

Python date, datetime, timedelta, and timezone, including naive versus aware values and ISO format conversion.

模块页正文目前为英文。

datetime is a standard-library module. A naive datetime has tzinfo set to None and does not represent a timezone. An aware datetime has tzinfo set and can be converted between zones.

Examples on this page use fixed calendar values so the output does not depend on the current time. datetime.now() and date.today() return the current clock and are a poor fit for expected-output examples.

Examples were checked against Python 3.13. See the official documentation for the complete API.

Python reference overview →

date and timedelta

datetime.date stores a calendar date. datetime.timedelta stores a duration. Adding a timedelta to a date yields another date, which is useful for date arithmetic that should not be done by adding raw day numbers.

date and timedelta arithmetic

date(year, month, day)
date.isoformat()
timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

Construct a calendar date and shift it by a duration.

Raises

  • ValueError — Raised when the year, month, or day is out of range, for example date(2026, 2, 31).
python
from datetime import date, timedelta

start = date(2026, 11, 21)
print(start.isoformat())
print((start + timedelta(days=10)).isoformat())
print((start - date(2026, 11, 1)).days)

Expected output

2026-11-21
2026-12-01
20

Official documentation →

datetime and timezones

datetime.datetime.now(tz=None) returns the current local time when tz is omitted, which is naive. Pass a timezone, typically timezone.utc, to get an aware value. datetime.utcnow() still exists in Python 3.13 but has been deprecated since 3.12; use datetime.now(timezone.utc) instead.

You cannot safely compare or subtract a naive datetime and an aware datetime. Python raises TypeError.

aware datetime conversion

datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
datetime.now(tz=None)
datetime.fromisoformat(date_string)
datetime.isoformat(sep="T", timespec="auto")
datetime.astimezone(tz=None)

Build a fixed timezone-aware datetime, convert it between zones, and render ISO 8601 text.

  • fromisoformat() accepts the output of isoformat(), including offsets such as +00:00 and +08:00.
  • astimezone() on a naive datetime is treated as local time. Prefer constructing aware values explicitly.
python
from datetime import datetime, timedelta, timezone

moment = datetime(2026, 11, 21, 15, 30, tzinfo=timezone.utc)
print(moment.isoformat())
print(moment.astimezone(timezone(timedelta(hours=8))).isoformat())
print(datetime.fromisoformat("2026-11-21T15:30:00+00:00"))
try:
    moment - datetime(2026, 11, 21, 15, 30)
except TypeError as exc:
    print(type(exc).__name__)

Expected output

2026-11-21T15:30:00+00:00
2026-11-21T23:30:00+08:00
2026-11-21 15:30:00+00:00
TypeError

Official documentation →