Python Glossary Русский

all Python 3datetimefunction

datetime.datetime.fromtimestamp()

datetime methods

Creates a datetime from a Unix timestamp (seconds since 1970-01-01). In the local time zone by default; pass tz for UTC or another one.

Syntax

datetime.fromtimestamp(timestamp, tz=None)

Without tz the result is naive and expressed in whatever zone the machine happens to use, so the same timestamp reads differently on your laptop and on the server; pass timezone.utc when you need reproducibility. The companion utcfromtimestamp() is deprecated as of Python 3.12, and this call with tz is its replacement. The reverse direction is timestamp(), which likewise reads a naive object as local time.

Examples

from datetime import datetime, timezone
ts = 1704067200
local = datetime.fromtimestamp(ts)              # локальное время
utc   = datetime.fromtimestamp(ts, tz=timezone.utc)  # UTC
print(utc)  # 2024-01-01 00:00:00+00:00

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy