Unix Timestamp in Python

Python's time.time() returns the current Unix time as a float of seconds, while datetime.fromtimestamp(ts, tz=timezone.utc) converts a timestamp to an aware datetime. Always pass a tz to avoid local-time surprises.

Get & convert epoch time in Python

from datetime import datetime, timezone
print(datetime.fromtimestamp(1700000000, tz=timezone.utc))  # 2023-11-14T22:13:20.000Z
import time; int(time.time())
Gotcha: datetime.fromtimestamp() without a tz uses local time; use timezone.utc (or datetime.utcfromtimestamp, now deprecated) for UTC.

Frequently asked questions

How do I get the current Unix timestamp in Python?
int(time.time()) for seconds. Use time.time_ns() for nanoseconds.
How do I convert a timestamp to UTC in Python?
datetime.fromtimestamp(ts, tz=timezone.utc) returns a timezone-aware UTC datetime.

Other languages

Copied