pythontimeutcunix-timestamp

get current UTC posix timestamp in better resolution than seconds in Python


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:

  1. time.time_ns()

    • I thought this was it, but it's local time.
  2. 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
  3. 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.


Solution

  • 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.