Unix Timestamps
A Unix timestamp is seconds since 1970-01-01 UTC. Convert between datetime and timestamp for interop with APIs and databases.
A Unix timestamp is seconds since 1970-01-01 UTC. Convert between datetime and timestamp for interop with APIs and databases.
from datetime import datetime, timezone
import time
ts = time.time() # float seconds since epoch
dt = datetime.fromtimestamp(ts, tz=timezone.utc) # timestamp → datetime
ts2 = dt.timestamp() # datetime → timestamp
# From integer timestamp (e.g., API response)
api_ts = 1718456400
event = datetime.fromtimestamp(api_ts, tz=timezone.utc)
Always pass tz=timezone.utc to fromtimestamp() — without it, the result is local time.