I am trying to get a UTC posix timestamp in better resolution than seconds – milliseconds would be acceptable, but microseconds would be better. I need that as a synchronization for unrelated external counter/timer HW which runs in nanoseconds from 0 on powerup.
Which means I want some "absolute" time to have a pair of (my_absolute_utc_timestamp, some_counter_ns)
to be able to interpret subsequent counter/timer values.
And I need at least milliseconds precision. I'd like it to be an int
value, so I have no problems with floating point arithmetic precision loss.
time.time_ns()
time.mktime(time.gmtime())
>>> time.mktime(time.gmtime()) - datetime.datetime.utcnow().timestamp()
3599.555135011673
I ended up with int(datetime.datetime.utcnow() * 1000000)
as "utc_microseconds", which works, but:
Is there any better way to get microseconds or milliseconds UTC posix timestamp in Python? Using the Python standard library is preferred.
I'm using Python 3.10.
time.time_ns()
is the appropriate function for this.
It "returns time as an integer number of nanoseconds since the epoch." This is a "UTC timestamp", as the "epoch is the point where the time starts, the return value of time.gmtime(0). It is January 1, 1970, 00:00:00 (UTC) on all platforms."
Note that the source of the time information may offer less resolution than the function itself can express. Be sure to check time.get_clock_info('time')
for information on the underlying clock. As an example, on my MacOS the clock is limited to microsecond resolution.