How can I create a Python timestamp with millisecond granularity? How can I create a Python timestamp with millisecond granularity? python python

How can I create a Python timestamp with millisecond granularity?


import timetime.time() * 1000

where 1000 is milliseconds per second. If all you want is hundredths of a second since the epoch, multiply by 100.


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.