How can I create a Python timestamp with millisecond granularity?
In Python, datetime.now()
might produce a value with more precision than time.time()
:
from datetime import datetime, timezone, timedeltanow = datetime.now(timezone.utc)epoch = datetime(1970, 1, 1, tzinfo=timezone.utc) # use POSIX epochposix_timestamp_micros = (now - epoch) // timedelta(microseconds=1)posix_timestamp_millis = posix_timestamp_micros // 1000 # or `/ 1e3` for float
In theory, time.gmtime(0)
(the epoch used by time.time()
) may be different from 1970
.