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.
What have I tried:
time.time_ns()
- I thought this was it, but it's local time.
time.mktime(time.gmtime())
- for some strange reason, this is one hour more than utc time:
>>> time.mktime(time.gmtime()) - datetime.datetime.utcnow().timestamp() 3599.555135011673
- and it has only seconds precision
- for some strange reason, this is one hour more than utc time:
I ended up with
int(datetime.datetime.utcnow() * 1000000)
as "utc_microseconds", which works, but:- there may be problems with floating precision.
- it seems too complicated and I just don't like it.
Question:
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()
method returns the number of seconds since the epoch which is a UTC value.time_ns()
, and seconds fortime()
, with the decimals representing microseconds or what ever the system / OS allowstime
andtime_ns
return LOCAL time, Posix/Unix time has nothing to do with timezone. And you can check it: ` time.time() - datetime.datetime.utcnow().timestamp() => 7199.999995470047` (i.e. 2 hours difference which is correct for my timezone)