UnixTime / Reference
Unix time in Python
Convert Unix timestamps to timezone-aware Python datetimes and back, including 13-digit millisecond timestamps.
Get the current Unix timestamp in Python
Use datetime.now(timezone.utc) to create a timezone-aware UTC datetime. Calling .timestamp() returns Unix seconds as a float. Convert it to an integer if your application needs whole seconds.
from datetime import datetime, timezone
now_utc = datetime.now(timezone.utc)
unix_seconds = int(now_utc.timestamp())
print(unix_seconds) # Current Unix time in whole seconds
Convert Unix seconds to a UTC datetime
datetime.fromtimestamp() accepts seconds, not milliseconds. Pass tz=timezone.utc to get a timezone-aware object. Without that argument, Python produces a naive local datetime, which can cause mistakes when comparing or serializing timestamps.
from datetime import datetime, timezone
seconds = 1735689600
date = datetime.fromtimestamp(seconds, tz=timezone.utc)
print(date.isoformat()) # "2025-01-01T00:00:00+00:00"
Convert a 13-digit millisecond timestamp
Many JavaScript APIs and database exports use milliseconds. Divide by 1000 before passing the value to fromtimestamp. The resulting object is still interpreted according to the time zone you choose.
from datetime import datetime, timezone
milliseconds = 1735689600000
date = datetime.fromtimestamp(milliseconds / 1000, tz=timezone.utc)
print(date.strftime("%Y-%m-%d %H:%M:%S %Z"))
# 2025-01-01 00:00:00 UTC
Convert a UTC datetime back to a timestamp
A naive datetime has no offset information. Explicitly create a timezone-aware UTC datetime for reproducible results.
from datetime import datetime, timezone
date = datetime(2025, 1, 1, 0, 0, 0, tzinfo=timezone.utc)
seconds = int(date.timestamp())
print(seconds) # 1735689600
Potential pitfalls
- Seconds versus milliseconds: A 13-digit timestamp is often milliseconds; Python expects seconds.
- Local versus UTC: Use aware datetimes and convert with
.astimezone()when displaying regional times. - Fractional seconds: Floats can lose precision at the microsecond and especially nanosecond level. Use integer division or
Decimalwhen exact fractional timestamps matter. - Negative timestamps: Dates before 1970 have negative Unix timestamps. Some platforms have different date ranges; validate extreme values.
For a quick interactive check, use the UnixTime converter, which also handles microsecond and nanosecond integers.
Reference: Python datetime documentation.