Python Glossary Русский

Python 3.3+datetimefunction

datetime.datetime.timestamp()

datetime methods

Returns the Unix timestamp (seconds since 1970-01-01 00:00 UTC) as a float. The object has to be timezone-aware or local.

Syntax

datetime.timestamp() -> float

For a naive object Python assumes local machine time, so the very same code gives a different number on another computer or in CI. If you need a reproducible value, make the object aware, e.g. with tzinfo=timezone.utc. The result is a float, so a round trip can drift by the last microseconds — comparing timestamps for exact equality is fragile.

Examples

from datetime import datetime, timezone
dt = datetime(2024, 1, 1, tzinfo=timezone.utc)
print(dt.timestamp())  # 1704067200.0
from datetime import datetime, timezone
# обратно: datetime из timestamp
from datetime import datetime
dt2 = datetime.fromtimestamp(1704067200, tz=timezone.utc)

See also

Open in the full glossarydocs.python.orgReport an inaccuracy