Python Unix Timestamp Guide: datetime, timezone & zoneinfo

Written by Raheel Ikram | Updated December 5, 2026 | Reading time: 5 minutes

Calling .timestamp() on a naive Python datetime object uses your server's local timezone by mistake. When your code moves from a laptop in Karachi or New York to a cloud container running in UTC, all generated Unix timestamps shift by hours. Using timezone-aware objects stops this bug permanently.

Get the Current Unix Timestamp in Python

Python provides direct functions in the built-in time module for seconds and nanoseconds.

import time

# Float seconds (example: 1764892800.123456)
now_float = time.time()

# Whole integer seconds (10 digits)
now_sec = int(time.time())

# Integer nanoseconds (19 digits, Python 3.7+)
now_ns = time.time_ns()

Convert a Unix Timestamp to an Aware UTC Datetime

Older tutorials tell you to use datetime.utcfromtimestamp(). Starting in Python 3.12, both utcnow() and utcfromtimestamp() are deprecated because they create naive datetime objects without timezone metadata. Always pass tz=timezone.utc into datetime.fromtimestamp() instead, as recommended in the Python datetime documentation.

from datetime import datetime, timezone

unix_sec = 1764892800
dt_utc = datetime.fromtimestamp(unix_sec, tz=timezone.utc)
print(dt_utc.isoformat())
# Output: 2026-12-05T00:00:00+00:00

Handling 13-Digit Milliseconds From JavaScript APIs

Python's fromtimestamp() expects seconds, not milliseconds. Passing a 13-digit JavaScript value directly raises a ValueError: year is out of range error. Divide milliseconds by 1000 first.

ms_value = 1764892800500
dt = datetime.fromtimestamp(ms_value / 1000, tz=timezone.utc)
print(dt.isoformat())

Convert Unix Time to Any Real Timezone With zoneinfo

Since Python 3.9, the standard library includes zoneinfo.ZoneInfo, so you do not need third-party libraries like pytz for Daylight Saving Time rules.

from datetime import datetime
from zoneinfo import ZoneInfo

ts = 1764892800
ny_time = datetime.fromtimestamp(ts, tz=ZoneInfo("America/New_York"))
print(ny_time.isoformat())

Convert a Python Datetime Back to Unix Seconds

Always attach timezone.utc or a ZoneInfo object before calling .timestamp(). This guarantees the integer matches UTC on every machine.

from datetime import datetime, timezone

dt = datetime(2026, 12, 5, 0, 0, 0, tzinfo=timezone.utc)
epoch_int = int(dt.timestamp())
print(epoch_int) # 1764892800
About the Author: Raheel Ikram

Creator of Timestamp Converter, writing practical guides on timekeeping, SQL schema design, and web utilities. Read full bio.