Python Glossary Русский

all Python 3datetimefunction

datetime.datetime.astimezone()

datetime methods

Converts an aware datetime into another time zone. A naive object is treated as local time.

Syntax

dt.astimezone(tz=None)

The call does not move the instant, it only re-renders it: the underlying point in time stays the same while the visible clock fields and tzinfo change. The trap is calling it on a naive value that actually holds UTC — Python assumes the machine's local zone and shifts by the wrong amount. Use replace(tzinfo=...) to label a value with a zone, and astimezone() only to convert between zones.

Examples

from datetime import datetime, timezone, timedelta
utc = datetime(2024, 6, 17, 10, 0, tzinfo=timezone.utc)
msk = timezone(timedelta(hours=3))
msk_dt = utc.astimezone(msk)
print(msk_dt)  # 2024-06-17 13:00:00+03:00

See also

Open in the full glossarydocs.python.orgReport an inaccuracy