ZetCode

Python Unix timestamps

last modified November 19, 2026 Python 3.15

In this article we convert Unix timestamps to datetimes and back. A Unix timestamp, also called epoch time, is the number of seconds that have passed since 1970-01-01 00:00:00 UTC. Databases, log files, JSON APIs, and file systems store points in time in this form, because a single number is easy to store, compare, and sort.

The datetime article introduces fromtimestamp and timestamp, and the time module article shows the low-level clock functions. Here we look at the details that cause bugs: time zones, units other than seconds, values before 1970, and limits. The examples were run with the local time zone set to Europe/Bratislava.

A first timestamp

The time.time function returns the current timestamp as a float. The datetime.fromtimestamp method turns a timestamp into a datetime.

first_timestamp.py
import time
from datetime import UTC, datetime

print(time.time())
print(int(time.time()))
print(datetime.now(UTC).timestamp())

ts = 1_800_000_000
print(datetime.fromtimestamp(ts, UTC))

The float has a fractional part with sub-second precision; int cuts it off, which is the form most APIs expect. Calling timestamp on datetime.now(UTC) gives the same value. The timestamp 1 800 000 000 is January 15, 2027, at 8:00 UTC.

$ python first_timestamp.py
1795120460.3882124
1795120460
1795120460.388233
2027-01-15 08:00:00+00:00

One instant, many zones

A timestamp names an instant, not a wall-clock time. The tz argument of fromtimestamp only decides in which zone the instant is displayed.

same_instant.py
from datetime import UTC, datetime
from zoneinfo import ZoneInfo

ts = 1_800_000_000

utc = datetime.fromtimestamp(ts, UTC)
bratislava = datetime.fromtimestamp(ts, ZoneInfo("Europe/Bratislava"))
tokyo = datetime.fromtimestamp(ts, ZoneInfo("Asia/Tokyo"))
new_york = datetime.fromtimestamp(ts, ZoneInfo("America/New_York"))

for dt in (utc, bratislava, tokyo, new_york):
    print(dt, dt.timestamp())

print(utc == tokyo == new_york)

The four datetimes show different clock times, but they are the same instant: each converts back to the same timestamp, and aware datetimes compare equal across zones. Time zones are covered in the zoneinfo article.

$ python same_instant.py
2027-01-15 08:00:00+00:00 1800000000.0
2027-01-15 09:00:00+01:00 1800000000.0
2027-01-15 17:00:00+09:00 1800000000.0
2027-01-15 03:00:00-05:00 1800000000.0
True

Naive conversions use local time

Without the tz argument, fromtimestamp returns a naive datetime in local time, and timestamp treats a naive datetime as local time.

naive_timestamps.py
from datetime import datetime

ts = 1_800_000_000
local = datetime.fromtimestamp(ts)
print(local, local.tzinfo)
print(local.timestamp())

first = datetime(2026, 10, 25, 2, 30)
second = first.replace(fold=1)
print(first.timestamp(), second.timestamp())
print(second.timestamp() - first.timestamp())

missing = datetime(2026, 3, 29, 2, 30)
print(missing.timestamp())
print(datetime.fromtimestamp(missing.timestamp()))

The naive result shows 9:00, the Bratislava wall time, with no time zone attached. The round trip works on the same machine, but the same code on a server in another zone gives a different datetime. Local time also has gaps and repeats. On October 25, 2026, the clock goes from 3:00 back to 2:00, so 2:30 happens twice; the fold attribute selects the first or the second occurrence, which are 3600 seconds apart. On March 29, 2026, 2:30 does not exist; Python still computes a timestamp, and converting it back gives 3:30.

$ python naive_timestamps.py
2027-01-15 09:00:00 None
1800000000.0
1792888200.0 1792891800.0
3600.0
1774747800.0
2026-03-29 03:30:00

The utcfromtimestamp round trip

Older code uses utcfromtimestamp to get UTC. The method returns a naive datetime, and the next timestamp call reads it as local time.

utc_roundtrip.py
from datetime import UTC, datetime

ts = 1_800_000_000

naive = datetime.utcfromtimestamp(ts)
print(naive)
print(naive.timestamp() - ts)

aware = datetime.fromtimestamp(ts, UTC)
print(aware)
print(aware.timestamp() - ts)

fixed = naive.replace(tzinfo=UTC)
print(fixed.timestamp() - ts)

Since Python 3.12 the method issues a DeprecationWarning. The naive result shows the correct UTC wall time, but converting it back loses an hour, because Bratislava is one hour ahead of UTC in January. The aware result from fromtimestamp(ts, UTC) converts back exactly. Naive UTC values that are already stored, for example in a database, are fixed by attaching the zone with replace(tzinfo=UTC).

$ python utc_roundtrip.py
/home/user/python/utc_roundtrip.py:5: DeprecationWarning: datetime.datetime.utcfromtimestamp() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.fromtimestamp(timestamp, datetime.UTC).
  naive = datetime.utcfromtimestamp(ts)
2027-01-15 08:00:00
-3600.0
2027-01-15 08:00:00+00:00
0.0
0.0

Milliseconds and nanoseconds

Not every timestamp counts seconds. JavaScript's Date.now and many JSON APIs use milliseconds, and time.time_ns returns nanoseconds as an integer.

precision.py
import time
from datetime import UTC, datetime, timedelta

EPOCH = datetime(1970, 1, 1, tzinfo=UTC)

print(time.time_ns())
print(time.time_ns() // 1_000_000)

ms = 1_800_000_000_250
print(datetime.fromtimestamp(ms / 1000, UTC))
print(EPOCH + timedelta(milliseconds=ms))

dt = datetime(2027, 1, 15, 8, 0, 0, 250_000, tzinfo=UTC)
print(int(dt.timestamp() * 1000))
print((dt - EPOCH) // timedelta(milliseconds=1))

ns = 1_800_000_000_123_456_789
print(ns / 1_000_000_000)
print(datetime.fromtimestamp(ns / 1_000_000_000, UTC))
print(EPOCH + timedelta(microseconds=ns // 1000))

Dividing milliseconds by 1000 and passing the float to fromtimestamp works, but adding a timedelta to the epoch stays in integers and is exact. In the other direction, floor division of the difference by timedelta(milliseconds=1) gives an exact integer. Floats are the problem with nanoseconds: a double has about 16 significant digits, so the nanosecond value loses its last digits, and the datetime ends in 457 instead of 456. A datetime stores microseconds, so the nanoseconds are truncated in any case.

$ python precision.py
1795120460444097819
1795120460444
2027-01-15 08:00:00.250000+00:00
2027-01-15 08:00:00.250000+00:00
1800000000250
1800000000250
1800000000.1234567
2027-01-15 08:00:00.123457+00:00
2027-01-15 08:00:00.123456+00:00

Guessing the unit

When data comes from several sources, a timestamp may be in seconds, milliseconds, microseconds, or nanoseconds. The number of digits tells them apart for dates in the present.

guess_unit.py
from datetime import UTC, datetime, timedelta

EPOCH = datetime(1970, 1, 1, tzinfo=UTC)

UNITS = [
    (10**17, "nanoseconds", 10**9),
    (10**14, "microseconds", 10**6),
    (10**11, "milliseconds", 10**3),
    (0, "seconds", 1),
]


def from_epoch(value):
    for limit, name, per_second in UNITS:
        if abs(value) >= limit:
            seconds, rest = divmod(value, per_second)
            micros = rest * 1_000_000 // per_second
            return name, EPOCH + timedelta(seconds=seconds, microseconds=micros)


values = [1_800_000_000, 1_800_000_000_250, 1_800_000_000_250_500,
          1_800_000_000_250_500_700, 946_684_800]

for value in values:
    name, dt = from_epoch(value)
    print(f"{value:>25} {name:>12}  {dt}")

try:
    datetime.fromtimestamp(1_800_000_000_250, UTC)
except ValueError as e:
    print("ValueError:", e)

A timestamp in seconds reaches 1011 only in the year 5138, so larger values must be in a finer unit. The from_epoch function checks the limits from the largest down, splits the value into whole seconds and a remainder, and converts the remainder to microseconds. Passing a millisecond value to fromtimestamp as seconds raises ValueError, because it points to the year 59009. The guess fails for millisecond values before March 1973, which look like seconds.

$ python guess_unit.py
               1800000000      seconds  2027-01-15 08:00:00+00:00
            1800000000250 milliseconds  2027-01-15 08:00:00.250000+00:00
         1800000000250500 microseconds  2027-01-15 08:00:00.250500+00:00
      1800000000250500700  nanoseconds  2027-01-15 08:00:00.250500+00:00
                946684800      seconds  2000-01-01 00:00:00+00:00
ValueError: year must be in 1..9999, not 59009

Negative timestamps

Instants before 1970 have negative timestamps. Python handles them like any other value.

negative.py
from datetime import UTC, datetime, timedelta

EPOCH = datetime(1970, 1, 1, tzinfo=UTC)

print(datetime.fromtimestamp(-1, UTC))

landing = datetime(1969, 7, 20, 20, 17, 40, tzinfo=UTC)
ts = landing.timestamp()
print(ts)
print(datetime.fromtimestamp(ts, UTC))

old = datetime(1900, 1, 1, tzinfo=UTC)
print(old.timestamp())
print(EPOCH + timedelta(seconds=-2_208_988_800))

print(divmod(-14_182_940, 86_400))

One second before the epoch is the last second of 1969, and the first moon landing has a negative timestamp. On some platforms, notably Windows, fromtimestamp rejects negative values with an OSError; adding a timedelta to the epoch works everywhere. The last line shows why floor division matters: the moon landing is 165 days before the epoch, plus 73 060 seconds, or 20:17:40, into that day.

$ python negative.py
1969-12-31 23:59:59+00:00
-14182940.0
1969-07-20 20:17:40+00:00
-2208988800.0
1900-01-01 00:00:00+00:00
(-165, 73060)

The year 2038

Systems that store timestamps in a signed 32-bit integer stop on January 19, 2038. Python integers have no such limit, but the data we exchange with such systems does.

year2038.py
import struct
from datetime import UTC, datetime

limit = 2**31 - 1
print(datetime.fromtimestamp(limit, UTC))
print(datetime.fromtimestamp(-2**31, UTC))

print(struct.pack("<i", limit).hex())
try:
    struct.pack("<i", limit + 1)
except struct.error as e:
    print("struct.error:", e)

print(struct.pack("<q", limit + 1).hex())
print(datetime.fromtimestamp(limit + 1, UTC))

print(datetime.max.replace(tzinfo=UTC).timestamp())
try:
    datetime.fromtimestamp(10**12, UTC)
except ValueError as e:
    print("ValueError:", e)

The largest 32-bit value is 03:14:07 UTC on January 19, 2038, and the smallest is in December 1901. The struct module shows what happens when a timestamp is written to a 32-bit field: one second later does not fit. A 64-bit field (q) holds it, and Python converts it without problems. The real limit in Python is the year 9999 of datetime.max.

$ python year2038.py
2038-01-19 03:14:07+00:00
1901-12-13 20:45:52+00:00
ffffff7f
struct.error: 'i' format requires -2147483648 <= number <= 2147483647
0000008000000000
2038-01-19 03:14:08+00:00
253402300800.0
ValueError: year must be in 1..9999, not 33658

Days and leap seconds

In Unix time every day has exactly 86 400 seconds. Local days do not.

day_lengths.py
from datetime import UTC, datetime, timedelta
from zoneinfo import ZoneInfo

local = ZoneInfo("Europe/Bratislava")

for day in (24, 25, 26):
    start = datetime(2026, 10, day, tzinfo=local)
    end = start + timedelta(days=1)
    print(start.date(), end.timestamp() - start.timestamp())

start = datetime(2016, 12, 31, tzinfo=UTC)
end = datetime(2017, 1, 1, tzinfo=UTC)
print(end.timestamp() - start.timestamp())

try:
    datetime(2016, 12, 31, 23, 59, 60)
except ValueError as e:
    print("ValueError:", e)

October 25, 2026, the day when daylight saving time ends in Bratislava, is 25 hours long, so its timestamps are 90 000 seconds apart. Dividing a difference of local timestamps by 86 400 to count days is therefore wrong around time changes. The leap second at the end of 2016 does not show up at all: Unix time ignores leap seconds, and datetime rejects a seconds value of 60.

$ python day_lengths.py
2026-10-24 86400.0
2026-10-25 90000.0
2026-10-26 86400.0
86400.0
ValueError: second must be in 0..59, not 60

File times

File systems store modification times as timestamps. The stat method reads them, and os.utime sets them.

file_times.py
import os
from datetime import UTC, datetime
from pathlib import Path

path = Path("report.txt")
path.write_text("quarterly figures\n")

os.utime(path, ns=(1_800_000_000_000_000_000, 1_800_000_000_123_456_789))

st = path.stat()
print(st.st_mtime)
print(st.st_mtime_ns)
print(datetime.fromtimestamp(st.st_mtime, UTC))

modified = datetime(2026, 11, 19, 9, 15, tzinfo=UTC)
os.utime(path, (modified.timestamp(), modified.timestamp()))
print(datetime.fromtimestamp(path.stat().st_mtime, UTC))

age = datetime.now(UTC).timestamp() - path.stat().st_mtime
print(f"modified {age / 3600:.0f} hours ago")

The st_mtime attribute is a float, and st_mtime_ns is an exact integer in nanoseconds. With the ns argument, os.utime sets the times exactly; without it, it takes two floats for the access and modification times. The age of a file is the difference between the current timestamp and its modification time; it depends on when the program runs.

$ python file_times.py
1800000000.1234567
1800000000123456789
2027-01-15 08:00:00.123457+00:00
2026-11-19 09:15:00+00:00
modified 11 hours ago

An event log

We finish with a log file whose lines start with a timestamp in milliseconds, a format common in web applications.

events.log
1800000000250 login alice
1800000412900 upload alice report.pdf
1800001810050 login bob
1800003533120 logout alice
1800004020000 upload bob slides.odp
1800007204480 logout bob

The log records logins, uploads, and logouts of two users.

event_log.py
from collections import Counter
from datetime import UTC, datetime, timedelta
from zoneinfo import ZoneInfo

EPOCH = datetime(1970, 1, 1, tzinfo=UTC)
local = ZoneInfo("Europe/Bratislava")

events = []
with open("events.log") as f:
    for line in f:
        ms, action, user, *rest = line.split()
        when = EPOCH + timedelta(milliseconds=int(ms))
        events.append((when.astimezone(local), action, user, rest))

for when, action, user, rest in events:
    print(f"{when:%Y-%m-%d %H:%M:%S.%f}"[:-3], action, user, *rest)

per_hour = Counter(when.strftime("%H:00") for when, *_ in events)
print(dict(per_hour))

logins = {}
for when, action, user, rest in events:
    if action == "login":
        logins[user] = when
    elif action == "logout":
        print(user, "session:", when - logins.pop(user))

Each timestamp is converted exactly with timedelta and shown in local time with millisecond precision; slicing off the last three digits of %f turns microseconds into milliseconds. A Counter groups the events by local hour, and the difference between a login and the following logout gives the session length as a timedelta, covered in the timedelta article.

$ python event_log.py
2027-01-15 09:00:00.250 login alice
2027-01-15 09:06:52.900 upload alice report.pdf
2027-01-15 09:30:10.050 login bob
2027-01-15 09:58:53.120 logout alice
2027-01-15 10:07:00.000 upload bob slides.odp
2027-01-15 11:00:04.480 logout bob
{'09:00': 4, '10:00': 1, '11:00': 1}
alice session: 0:58:52.870000
bob session: 1:29:54.430000

Source

datetime – datetime.fromtimestamp

time – time.time_ns

os – os.utime

In this article we have converted Unix timestamps in seconds, milliseconds, and nanoseconds, handled naive and aware results, values before 1970, the 32-bit limit, and file times. See also Python datetime, Python zoneinfo, Python format datetime, and Python time module.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.