How do you get the current timestamp in milliseconds in Python? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you get the current timestamp in milliseconds in Python?

message-square
0

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_000 beats int(time.time() * 1000):
    • time.time() returns an IEEE-754 64-bit float (53 bits of significand). Multiplying a ~1.79 billion second epoch timestamp by 1000 approaches the sub-millisecond precision boundary of float64 and introduces binary floating-point rounding artifacts, whereas time.time_ns() // 1_000_000 uses exact 64-bit integer nanosecond division.
  • Avoid naive datetime.now().timestamp() (timezone trap):
    • Calling .timestamp() on a naive datetime.now() assumes the OS’s local timezone rather than UTC, which can miscalculate timestamps across daylight saving transitions or misconfigured containers. Always pass timezone.utc (datetime.now(timezone.utc).timestamp()).
  • 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 (or time.monotonic_ns() // 1_000_000).
  • Rounding vs. truncation (round vs. //):
    • time.time_ns() // 1_000_000 truncates sub-millisecond nanoseconds toward zero (standard behavior for database/API event timestamps like Java System.currentTimeMillis() and JavaScript Date.now()). Use round(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).