These Python examples use Unix seconds for the portable baseline and show milliseconds only where the runtime exposes them naturally. The question to answer before copying a snippet is simple: what unit does the next API expect?
Get the current Unix time
import time
seconds = int(time.time())
milliseconds = time.time_ns() // 1_000_000
Convert a timestamp to UTC
from datetime import datetime, timezone
instant = datetime.fromtimestamp(1700000000, tz=timezone.utc)
print(instant.isoformat())
Production note
Use timezone-aware datetime values for conversion and display. datetime.fromtimestamp without tz uses the machine local timezone.
Keep the unit in the field name when a value crosses a boundary: createdAtSeconds and createdAtMs are longer than createdAt, but much less mysterious during an incident.
Frequent questions:
- Q: Does time.time() return an integer?
- A: No. It returns seconds as a floating-point value. Wrap it with int() for whole Unix seconds, or multiply before rounding when you need milliseconds.
- Q: Should datetime values be naive or timezone-aware?
- A: Use timezone-aware UTC datetime values for APIs, databases, and logs. Naive datetime values are best avoided at system boundaries because their timezone meaning is implicit.