Use time.time_ns() // 1_000_000 (Python 3.7+) to get the current Unix epoch timestamp in integer milliseconds directly from nanosecond system clock resolution without floating-point precision loss—or int(datetime.now(timezone.utc).timestamp() * 1000) when working with timezone-aware datetime objects.
Basic Example
from datetime import datetime, timezone
import time
# 1. Recommended (fastest, exact integer arithmetic, no float precision drift):
timestamp_ms = time.time_ns() // 1_000_000
print(timestamp_ms)
# Output: 1795935840123
# 2. Using timezone-aware datetime (UTC):
dt_ms = int(datetime.now(timezone.utc).timestamp() * 1000)
print(dt_ms)
# Output: 1795935840123
# 3. Round-tripping a millisecond timestamp back to an aware UTC datetime:
dt_restored = datetime.fromtimestamp(timestamp_ms / 1000, tz=timezone.utc)
print(dt_restored.isoformat())
# Output: 2026-11-29T07:04:00.123000+00:00
Key Details & Edge Cases
- Why
time.time_ns() // 1_000_000beatsint(time.time() * 1000):time.time()returns an IEEE-754 64-bitfloat(53 bits of significand). Multiplying a ~1.79 billion second epoch timestamp by1000approaches the sub-millisecond precision boundary offloat64and introduces binary floating-point rounding artifacts, whereastime.time_ns() // 1_000_000uses exact 64-bit integer nanosecond division.
- Avoid naive
datetime.now().timestamp()(timezone trap):- Calling
.timestamp()on a naivedatetime.now()assumes the OS’s local timezone rather than UTC, which can miscalculate timestamps across daylight saving transitions or misconfigured containers. Always passtimezone.utc(datetime.now(timezone.utc).timestamp()).
- Calling
- Never use wall-clock timestamps (
time.time_ns()) to measure elapsed durations or benchmark code:- System wall clocks can jump backward or forward due to NTP clock syncs or manual time adjustments. For benchmarking or measuring intervals in milliseconds, always use
time.perf_counter_ns() // 1_000_000(ortime.monotonic_ns() // 1_000_000).
- System wall clocks can jump backward or forward due to NTP clock syncs or manual time adjustments. For benchmarking or measuring intervals in milliseconds, always use
- Rounding vs. truncation (
roundvs.//):time.time_ns() // 1_000_000truncates sub-millisecond nanoseconds toward zero (standard behavior for database/API event timestamps like JavaSystem.currentTimeMillis()and JavaScriptDate.now()). Useround(time.time_ns() / 1_000_000)only if you specifically need nearest-millisecond rounding.
Comparison of Millisecond Timestamp Methods in Python
| Method | Return Type | Clock Type | Float Rounding Risk? | Best Used When |
|---|---|---|---|---|
time.time_ns() // 1_000_000 (Recommended) |
int |
Wall clock (Unix epoch UTC) | No (exact integer math) | Generating Unix epoch millisecond timestamps for APIs, JSON payloads, and databases. |
int(datetime.now(timezone.utc).timestamp() * 1000) |
int |
Wall clock (Unix epoch UTC) | Minor (float64 scale) |
Converting an existing timezone-aware datetime object into epoch milliseconds. |
int(time.time() * 1000) |
int |
Wall clock (Unix epoch UTC) | Minor (float64 scale) |
Legacy Python <3.7 codebases where time_ns() is unavailable. |
time.perf_counter_ns() // 1_000_000 |
int |
Monotonic high-res timer | No (exact integer math) | Measuring elapsed milliseconds between two points in code (never affected by NTP jumps). |
You must log in or register to comment.
