Python timestamps

datetime and Unix time, without the timezone trap. Rule one: bare fromtimestamp() returns local time.

[MOD.DEMO // TRY]

TRY IT — PASTE A STAMP

—

Now, in seconds

import math
import time
now_s = math.floor(time.time())

Now, in milliseconds

import math
import time
now_ms = math.floor(time.time() * 1000)

Stamp to aware datetime

from datetime import datetime, timezone
ts = 1712345678
dt = datetime.fromtimestamp(ts, tz=timezone.utc)
print(dt.isoformat())  # 2024-04-05T19:34:38+00:00

Aware datetime back to stamp

import math
from datetime import datetime, timedelta, timezone
dt = datetime(2024, 4, 5, 21, 34, 38, tzinfo=timezone(timedelta(hours=2)))
ts = math.floor(dt.timestamp())
print(ts)  # 1712345678; preserve the original offset

JS milliseconds into Python

from datetime import datetime, timezone
ms = 1712345678000
dt = datetime.fromtimestamp(ms / 1000, tz=timezone.utc)
print(dt.isoformat())

THE TIMEZONE PITFALL

fromtimestamp(ts) without tz uses the server local zone: UTC+8 in Shanghai; Berlin uses UTC+1 in winter and UTC+2 during daylight saving time (DST). Pass tz=timezone.utc for UTC output and use .astimezone() for display. Preserve an aware datetime’s offset when calling .timestamp(). Reject naive datetimes unless their source zone is known; replacing tzinfo is not a timezone conversion.

[DOC.FAQ // INDEX]

ANSWERS

05 ITEMS
01 How do I get the current Unix timestamp in Python?

Import math and time, then use math.floor(time.time()) for seconds or math.floor(time.time()*1000) for milliseconds. floor rounds down, including for negative epochs; int truncates toward zero. The standalone examples above include the imports.

02 Why is fromtimestamp off by hours?

Bare datetime.fromtimestamp(ts) returns local wall time for that instant. Pass tz=timezone.utc explicitly, then .astimezone() for display. Unix time identifies an instant independently of the display timezone.

03 How do I convert JS Date.now() in Python?

Divide milliseconds by 1000 before passing them to datetime.fromtimestamp, as in the complete example above. That Python API expects seconds. Passing a contemporary millisecond value as seconds exceeds the supported date range and can raise ValueError, OverflowError or OSError, depending on the platform.

04 How do I convert a datetime back to a stamp?

Use math.floor(dt.timestamp()) for an aware datetime, preserving its existing offset; the complete example above creates one with UTC+02:00. floor handles pre-1970 fractional timestamps correctly. Do not overwrite the offset with replace(tzinfo=UTC). Reject naive values unless their source timezone is known and explicitly resolved.

05 Seconds or milliseconds for storage?

Choose the unit and precision required by your API or database, and document them explicitly. Python datetime.timestamp() returns seconds; JavaScript Date uses milliseconds. Neither unit nor precision is universal across backends. JavaScript Number represents integers exactly only within its safe-integer range (±(2^53−1)).

[NAV.SUITE]

KEEP EXPLORING TOOLKITS

3 PAGES
[DOC.LINKS]

ALSO WORTH A LOOK

Independent alternatives, listed for cross-checking. Presence here is not an endorsement, and corrections are welcome.

Sources and specifications