Python Timestamp: Get and Convert Epoch Time

TL;DR: the three lines most people need
import time
from datetime import datetime, timezone

ts = int(time.time())                             # now, in seconds
dt = datetime.fromtimestamp(ts, tz=timezone.utc)  # timestamp → datetime
back = int(dt.timestamp())                        # datetime → timestamp

Tested on: Python 3.12 · last tested

A Python timestamp is a Unix time value: seconds since 00:00:00 UTC on 1 January 1970. This guide shows how to read epoch time in Python, turn it into a datetime and back, and avoid the time zone traps that cause most bugs. It is part of the Unix timestamp guides. To check a value by hand, use the epoch converter.

Get the Current Epoch Time in Python

The time module reads the system clock directly. time.time() returns a float with a fractional part, so the shortest epoch time Python one-liner is int(time.time()), which gives the usual 10-digit value.

import time

print(time.time())       # float seconds
print(int(time.time()))  # whole seconds
print(time.time_ns())    # integer nanoseconds
Example output at 2025-01-01T00:00:00Z
1735689600.123456
1735689600
1735689600123456789

For epoch time in Python as an object rather than a number, ask datetime for the current UTC time. Always pass a time zone: the result is then “aware” and safe to compare and convert.

from datetime import datetime, timezone

now = datetime.now(timezone.utc)
print(now.isoformat())
print(int(now.timestamp()))
Example output at 2025-01-01T00:00:00Z
2025-01-01T00:00:00.123456+00:00
1735689600

To see the live value and compare, open the current epoch time page.

Convert a Unix Timestamp to a Python datetime

For Python timestamp to datetime conversion, use datetime.fromtimestamp() with a tz argument. Without it, Python converts to the local zone of whatever machine runs the code.

from datetime import datetime, timezone

dt = datetime.fromtimestamp(1735689600, tz=timezone.utc)
print(dt)
print(dt.isoformat())
Output
2025-01-01 00:00:00+00:00
2025-01-01T00:00:00+00:00

Convert to a specific time zone

The standard library's zoneinfo module (Python 3.9+) reads the IANA time zone database.

from datetime import datetime
from zoneinfo import ZoneInfo

ny = datetime.fromtimestamp(1735689600, tz=ZoneInfo("America/New_York"))
print(ny)
Output
2024-12-31 19:00:00-05:00

Pitfall on Windows: Windows has no system copy of the IANA database, so this raises ZoneInfoNotFoundError: 'No time zone found with key America/New_York'. Install the data package with pip install tzdata and the same code works.

Convert a datetime to a Timestamp

For Python datetime to timestamp conversion, call .timestamp() on an aware datetime. It returns a float, so wrap it in int() when you need whole seconds.

from datetime import datetime, timezone

dt = datetime(2025, 1, 1, tzinfo=timezone.utc)
print(dt.timestamp())
print(int(dt.timestamp()))
Output
1735689600.0
1735689600

Strings in ISO 8601 format parse with fromisoformat(). Since Python 3.11 it also accepts the Z suffix.

from datetime import datetime

dt = datetime.fromisoformat("2025-01-01T00:00:00Z")
print(dt, int(dt.timestamp()))
Output
2025-01-01 00:00:00+00:00 1735689600

Pitfall: calling .timestamp() on a naive datetime (no tzinfo) treats it as local time, so the answer changes from machine to machine. If your naive values are really UTC, attach the zone with dt.replace(tzinfo=timezone.utc), or use calendar.timegm(), which always reads the tuple as UTC:

import calendar
from datetime import datetime

naive_utc = datetime(2025, 1, 1)
print(calendar.timegm(naive_utc.timetuple()))
Output
1735689600

Python Timestamps in Milliseconds and Nanoseconds

JavaScript, Java and many APIs send a Python milliseconds timestamp your way as a 13-digit integer. Divide by 1,000 before converting; the float keeps the milliseconds.

from datetime import datetime, timezone

ms = 1735689600123
dt = datetime.fromtimestamp(ms / 1000, tz=timezone.utc)
print(dt.isoformat(timespec="milliseconds"))
print(int(dt.timestamp() * 1000))  # back to ms
Output
2025-01-01T00:00:00.123+00:00
1735689600123

To produce milliseconds from the clock, use integer math on time.time_ns() so floating point never rounds the last digit: time.time_ns() // 1_000_000.

A datetime only stores microseconds, so nanosecond values need integer division. Split the seconds from the remainder:

from datetime import datetime, timedelta, timezone

ns = 1735689600123456789
dt = datetime.fromtimestamp(ns // 1_000_000_000, tz=timezone.utc) \
     + timedelta(microseconds=ns % 1_000_000_000 // 1000)
print(dt.isoformat())
Output
2025-01-01T00:00:00.123456+00:00

The last three digits (789 ns) are dropped because datetime cannot hold them. If they matter, keep the original integer alongside the datetime, and use it for sorting and comparisons.

Time Zones: Why utcfromtimestamp Is Deprecated

Older tutorials use datetime.utcfromtimestamp() and datetime.utcnow(). Both are deprecated since Python 3.12, because they return naive datetimes that look like local time but hold UTC values. Mixing them with aware datetimes produces silent hour-long errors. Running the old call now prints:

from datetime import datetime

old = datetime.utcfromtimestamp(1735689600)
print(old, old.tzinfo)
Output
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).
2025-01-01 00:00:00 None

The fix is a one-line swap. datetime.UTC (3.11+) and timezone.utc are the same object.

Deprecated calls and replacements
DeprecatedUse instead
datetime.utcfromtimestamp(ts)datetime.fromtimestamp(ts, tz=timezone.utc)
datetime.utcnow()datetime.now(timezone.utc)

Daylight saving and datetime arithmetic

Aware datetimes with a ZoneInfo zone do “wall clock” arithmetic. Adding one day keeps the same local time, even when a daylight saving change makes that day 23 or 25 hours long:

from datetime import datetime, timedelta
from zoneinfo import ZoneInfo

ny = ZoneInfo("America/New_York")
start = datetime(2026, 3, 7, 12, 0, tzinfo=ny)
later = start + timedelta(days=1)
print(later, (later.timestamp() - start.timestamp()) / 3600)
Output
2026-03-08 12:00:00-04:00 23.0

That is usually what people want for calendar events, but not for timeouts or billing periods. For elapsed time, do the math on Unix timestamps or on UTC datetimes, where every hour is 3,600 seconds, and convert to a local zone only for display.

The JavaScript timestamp guide covers the same aware-vs-local idea for front-end code.

Convert an Epoch Column to Dates in pandas

For pandas epoch to datetime conversion, never loop over rows. Pass the whole column to pd.to_datetime() with the right unit and utc=True:

import pandas as pd

df = pd.DataFrame({"ts": [1735689600, 1735693200, 1735779600]})
df["when"] = pd.to_datetime(df["ts"], unit="s", utc=True)
print(df)
Output
           ts                      when
0  1735689600 2025-01-01 00:00:00+00:00
1  1735693200 2025-01-01 01:00:00+00:00
2  1735779600 2025-01-02 01:00:00+00:00

Use unit="ms" for 13-digit values and unit="us" or unit="ns" for longer ones. To show local times, convert the aware column:

df["ny"] = df["when"].dt.tz_convert("America/New_York")
print(df[["ts", "ny"]])
Output
           ts                        ny
0  1735689600 2024-12-31 19:00:00-05:00
1  1735693200 2024-12-31 20:00:00-05:00
2  1735779600 2025-01-01 20:00:00-05:00

To turn the column back into epoch seconds, subtract the epoch and divide by one second. This works at any datetime resolution:

epoch = pd.Timestamp("1970-01-01", tz="UTC")
df["back"] = (df["when"] - epoch) // pd.Timedelta("1s")
print(df["back"].tolist())
Output
[1735689600, 1735693200, 1735779600]

Pitfall: the old trick .astype("int64") // 10**9 assumes nanosecond storage. In pandas 3 these columns are stored as datetime64[us, UTC], so that trick is off by a factor of 1,000. The subtraction above has no such dependency. Tested with pandas 3.1. Storing the result in a database? See Postgres epoch to timestamp.

Common Python Timestamp Errors

Most Python timestamp bugs fall into four groups. Each one below shows the real error message.

Milliseconds passed as seconds

datetime.fromtimestamp(1735689600000, tz=timezone.utc)
Output on Windows
OSError: [Errno 22] Invalid argument

A 13-digit value read as seconds is tens of thousands of years away. Linux and macOS raise a different exception for the same mistake, but the cause is identical: divide by 1,000.

Negative timestamps on Windows

datetime.fromtimestamp(-86400, tz=timezone.utc)
Output on Windows
OSError: [Errno 22] Invalid argument

Windows' C library rejects dates before 1970, even in UTC. Add a timedelta to the epoch instead, which works on every platform:

from datetime import datetime, timedelta, timezone

epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
print(epoch + timedelta(seconds=-86400))
Output
1969-12-31 00:00:00+00:00

Comparing naive and aware datetimes

datetime(2025, 1, 1) < datetime(2025, 1, 1, tzinfo=timezone.utc)
Output
TypeError: can't compare offset-naive and offset-aware datetimes

Make every datetime aware at the edge of your program, right where it is parsed or created, and the error disappears.

Strings instead of numbers

Timestamps read from CSV files, environment variables or query strings arrive as text. fromtimestamp() does not convert them for you:

datetime.fromtimestamp("1735689600", tz=timezone.utc)
Output
TypeError: 'str' object cannot be interpreted as an integer

Convert first with int(value), or float(value) when the text may contain a decimal part. Do it once where the data enters your program, and validate the length there too, so a millisecond value cannot slip through as seconds. A simple check is that a present-day value in seconds has exactly 10 digits.

Float precision

time.time() returns a float, which holds about 15 to 16 significant digits. That is enough for microseconds on present-day values, but adding or subtracting many small floats slowly accumulates error. When exact values matter, as in event ordering or deduplication keys, use the integer time.time_ns() and convert at the end.

Missing time zone data

ZoneInfoNotFoundError on Windows or in slim Docker images means the IANA database is missing. Install tzdata from pip, or the tzdata system package in the image.

Python timestamp questions

How do I get the current timestamp in Python?

Call time.time() for a float in seconds, or int(time.time()) for the usual 10-digit integer. Use time.time_ns() for an exact integer in nanoseconds, and datetime.now(timezone.utc) when you want an aware datetime object instead of a number. All of them read the same system clock and count from 00:00:00 UTC on 1 January 1970.

Why does datetime.fromtimestamp() give me the wrong hour?

Without a tz argument, fromtimestamp() converts to the machine's local time zone and returns a naive datetime, so the result depends on where the code runs. Pass tz=timezone.utc to get UTC, or a ZoneInfo object for a specific zone. Then print the datetime with isoformat() so the offset is visible and the hour is never ambiguous.

How do I convert a millisecond timestamp in Python?

Divide by 1,000 before calling fromtimestamp: datetime.fromtimestamp(ms / 1000, tz=timezone.utc). The float keeps the milliseconds as microseconds in the datetime. To go back, multiply dt.timestamp() by 1,000 and convert to int. In pandas, pass unit="ms" to pd.to_datetime() instead of dividing the whole column yourself.