Unix timestamps in Python

Python gives you seconds as a float. The usual bug is a naive datetime, one with no time zone attached, being treated as local time.

Current timestamp

print(int(time.time()))                # → e.g. 1763164800     seconds
print(time.time_ns() // 1_000_000)     # → e.g. 1763164800123  milliseconds

time.time() is a float with a fractional part. Use time.time_ns() when you need an exact integer, for example for milliseconds.

Timestamp to datetime

Every example uses 1700000000, which is 14 November 2023 at 22:13:20 UTC, so you can compare the output across languages or check it in the timestamp converter.

d = datetime.fromtimestamp(1700000000, tz=timezone.utc)
print(d.isoformat())                              # → 2023-11-14T22:13:20+00:00
print(d.strftime('%Y-%m-%d %H:%M:%S'))            # → 2023-11-14 22:13:20
new_york = timezone(timedelta(hours=-5))          # a fixed offset; use zoneinfo for real zones
print(d.astimezone(new_york).isoformat())         # → 2023-11-14T17:13:20-05:00

Always pass tz=. Without it, fromtimestamp returns a naive datetime in the machine's local time, and datetime.utcfromtimestamp(), which also returns a naive value, is deprecated since Python 3.12. For a named zone use zoneinfo.ZoneInfo('America/New_York') from the standard library (Python 3.9 and later; on Windows it needs the tzdata package installed).

Datetime to timestamp

print(int(datetime(2023, 11, 14, 22, 13, 20, tzinfo=timezone.utc).timestamp()))     # → 1700000000
print(int(datetime.fromisoformat('2023-11-14T22:13:20+00:00').timestamp()))         # → 1700000000
print(calendar.timegm((2023, 11, 14, 22, 13, 20)))                                  # → 1700000000

calendar.timegm takes a UTC time tuple and is the inverse of time.gmtime. time.mktime is its local-time counterpart; do not mix them up.

Pitfalls

naive = datetime(2023, 11, 14, 22, 13, 20)                   # no tzinfo: .timestamp() would assume local time
print(int(naive.replace(tzinfo=timezone.utc).timestamp()))   # → 1700000000
ms = 1700000000123
print(datetime.fromtimestamp(ms / 1000, tz=timezone.utc).isoformat(timespec='milliseconds'))   # → 2023-11-14T22:13:20.123+00:00
epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
print((epoch + timedelta(seconds=-86400)).date())           # → 1969-12-31   works for negative values on every platform
  • Naive datetimes. datetime(2023, 11, 14, 22, 13, 20).timestamp() assumes local time, so the result depends on where the code runs. Attach tzinfo first.
  • Milliseconds. fromtimestamp wants seconds; divide a 13-digit value by 1000.
  • Negative timestamps on Windows. datetime.fromtimestamp(-86400, tz=timezone.utc) raises OSError: [Errno 22] Invalid argument on Windows, because it relies on the C library. Adding a timedelta to the epoch works everywhere.
  • Floats. A float has about 15 to 16 significant digits, enough for microseconds today but not nanoseconds.

Questions

How do I get the current Unix timestamp in Python?

int(time.time()) for seconds, or time.time_ns() // 1_000_000 for milliseconds. Both need "import time".

What replaces datetime.utcnow() and utcfromtimestamp()?

datetime.now(timezone.utc) and datetime.fromtimestamp(ts, tz=timezone.utc). They return aware datetimes, so later conversions cannot silently assume local time. The old functions are deprecated since Python 3.12.

Why is my timestamp off by a few hours?

A naive datetime was treated as local time. Either create it with tzinfo=timezone.utc or call .replace(tzinfo=timezone.utc) before .timestamp().