Unix timestamps in Python

Get the current epoch time and convert between timestamps and dates in Python. Every snippet below is copy-ready.

// note

Always pass an explicit timezone; naive datetimes are the classic bug.

now.py · current timestamp
import time

now_seconds = int(time.time())
now_millis  = int(time.time() * 1000)
timestamp → date
from datetime import datetime, timezone

ts = 1700000000
dt = datetime.fromtimestamp(ts, tz=timezone.utc)
print(dt.isoformat())  # 2023-11-14T22:13:20+00:00
date → timestamp
from datetime import datetime, timezone

dt = datetime(2023, 11, 14, 22, 13, 20, tzinfo=timezone.utc)
ts = int(dt.timestamp())
// current epoch

— seconds since 1970-01-01T00:00:00Z.

Watch out for these

  • Seconds vs milliseconds. An epoch value 13 digits long is milliseconds; 10 digits is seconds. Mixing them gives dates in 1970 or 55828.
  • Local vs UTC. Format functions that default to the machine's timezone will silently differ between servers.
  • Leap seconds. Unix time ignores them — the count is a simple 86,400 seconds per day.

Reference: https://docs.python.org/3/library/datetime.html

advertisement