Python Glossary Русский

all Python 3datetimeterm

timezone aware datetime

timezone

A datetime that carries a time zone. Use timezone from datetime, or ZoneInfo from zoneinfo.

Syntax

from datetime import timezone
datetime.now(timezone.utc)

Naive and aware objects do not mix: subtracting or ordering datetime.now() and datetime.now(timezone.utc) raises TypeError, while == silently gives False, so pick one convention for the whole program — usually UTC. A timezone(timedelta(hours=3)) is a fixed offset that knows nothing about daylight saving; for real regions use zoneinfo.ZoneInfo("Europe/Berlin") from the standard library (Python 3.9+) instead of pytz.

Examples

from datetime import datetime, timezone, timedelta
utc_now = datetime.now(timezone.utc)
print(utc_now.tzinfo)  # → UTC
print(utc_now.utcoffset())  # → 0:00:00
moscow_tz = timezone(timedelta(hours=3))
moscow_now = datetime.now(moscow_tz)
print(moscow_now.utcoffset())  # → 3:00:00
print(moscow_now.strftime('%z'))  # → +0300
fixed = datetime(2024, 5, 17, 12, 30, tzinfo=timezone.utc)
print(fixed)  # → 2024-05-17 12:30:00+00:00
print(fixed.astimezone(moscow_tz))  # → 2024-05-17 15:30:00+03:00

See also

Open in the full glossarydocs.python.orgReport an inaccuracy