68

I've been trying to find a way to get the time since 1970-01-01 00:00:00 UTC in seconds and nanoseconds in python and I cannot find anything that will give me the proper precision.

I have tried using time module, but that precision is only to microseconds, so the code I tried was:

import time

print time.time()

which gave me a result like this:

1267918039.01

However, I need a result that looks like this:

1267918039.331291406

Does anyone know a possible way to express UNIX time in seconds and nanoseconds? I cannot find a way to set the proper precision or get a result in the correct format. Thank you for any help

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Bill
  • 709
  • 1
  • 6
  • 4

6 Answers6

57

Since Python 3.7 it's easy to achieve with time.time_ns()

Similar to time() but returns time as an integer number of nanoseconds since the epoch.

All new features that includes nanoseconds in Python 3.7 release: PEP 564: Add new time functions with nanosecond resolution

vishes_shell
  • 22,409
  • 6
  • 71
  • 81
  • 2
    This is neat native shortcut for time in nanoseconds!! However when I try to do `time.time_ns()`, it always outputs 000 for the nanoseconds precision. I can a more accurate precision by printing like this `"%.1f" % time.time_ns()`. Do you know why though? @vishes_shell – addicted Dec 24 '19 at 05:13
  • 1
    @addicted `time.time_ns()` returns *integer*, so there is no floating poin. I believe that nanoseconds is the most accurate you can get. – vishes_shell Dec 24 '19 at 07:41
  • Sorry maybe I was unclear. What I mean is that the integer ends with 000 everytime I use time_ns. Example, it returns 1577173496123123000 instead of 1577173496123123123. It shouldnt be 000 everytime even though it is integer. – addicted Dec 24 '19 at 07:46
  • 1
    @addicted https://stackoverflow.com/questions/53868389/time-time-ns-is-not-returing-nanoseconds-correctly-on-macos is highly relevant. – vishes_shell Dec 24 '19 at 14:29
47

Your precision is just being lost due to string formatting:

>>> import time
>>> print "%.20f" % time.time()
1267919090.35663390159606933594
MattH
  • 37,273
  • 11
  • 82
  • 84
  • 7
    Actually I can imagine that it is accurate to so many decimal places, but there is precision! :) – MattH Mar 06 '10 at 23:48
  • 4
    you mean that it is *not* accurate to so many decimal places. [`time.time()` on recent CPython uses the `clock_gettime(2)`, `GetSystemTimeAsFileTime()` depening on OS (you can call them on earlier Python versions too](http://stackoverflow.com/a/28574340/4279)) -- though probably the system time is not accurate enough even for old microseconds-based interfaces. – jfs Apr 26 '15 at 21:49
  • 8
    It's impossible to get nanosecond precision since 1970-04-15 from time.time no mater what formatting you are using, because time.time return float and it only have 53 bits significand precision which can only represent roughly 104 days in nanoseconds precision(9007199254740992 nanoseconds). – czz Nov 29 '17 at 08:49
  • 2
    This answer is deceptive because as others have mentioned there are various limits on precision of time. You can request as much precision as you can throw at it, it doesn't mean anything "real". `print('{:f}'.format(time.time()*1e99)) 1586191079196933855371082093348346232762798658965005626373153402400776535386890150019453108167635773543153664.000000` @martijn-pieters has the correct approach, `time.get_clock_info(name)` tells you how much you can actually get. The default printf is 6 decimal places (1 μs), which is the limit of precision of most implementations of time.time(). – DeusXMachina Apr 06 '20 at 16:41
  • Python 3 equivalent: `print("{:.20f}".format(time.time()))` – beeeliu Mar 15 '23 at 21:30
10

It depends on the type of clock and your OS and hardware wether or not you can even get nanosecond precision at all. From the time module documentation:

The precision of the various real-time functions may be less than suggested by the units in which their value or argument is expressed. E.g. on most Unix systems, the clock “ticks” only 50 or 100 times a second.

On Python 3, the time module gives you access to 5 different types of clock, each with different properties; some of these may offer you nanosecond precision timing. Use the time.get_clock_info() function to see what features each clock offers and what precision time is reported in.

On my OS X 10.11 laptop, the features available are:

>>> for name in ('clock', 'monotonic', 'perf_counter', 'process_time', 'time'):
...     print(name, time.get_clock_info(name), sep=': ')
...
clock: namespace(adjustable=False, implementation='clock()', monotonic=True, resolution=1e-06)
monotonic: namespace(adjustable=False, implementation='mach_absolute_time()', monotonic=True, resolution=1e-09)
perf_counter: namespace(adjustable=False, implementation='mach_absolute_time()', monotonic=True, resolution=1e-09)
process_time: namespace(adjustable=False, implementation='getrusage(RUSAGE_SELF)', monotonic=True, resolution=1e-06)
time: namespace(adjustable=True, implementation='gettimeofday()', monotonic=False, resolution=1e-06)

so using the time.monotonic() or time.perf_counter() functions would theoretically give me nanosecond resolution. Neither clock gives me wall time, only elapsed time; the values are otherwise arbitrary. They are however useful for measuring how long something took.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
9

The problem is probably related to your OS, not Python. See the documentation of the time module: http://docs.python.org/library/time.html

time.time()

Return the time as a floating point number expressed in seconds since the epoch, in UTC. Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls.

In other words: if your OS can't do it, Python can't do it. You can multiply the return value by the appropriate order of magnitude in order to get the nanosecond value, though, imprecise as it may be.

EDIT: The return is a float variable, so the number of digits after the comma will vary, whether your OS has that level of precision or not. You can format it with "%.nf" where n is the number of digits you want, though, if you want a fixed point string representation.

Alan Plum
  • 10,814
  • 4
  • 40
  • 57
  • 2
    I think the problem may be neither with the OS nor python... the problem is that there should be a way to get metadata on which is the greatest precision of time currently supported and a way to get time in that, and that we do not know it. :) – n611x007 Jun 13 '13 at 16:00
5

It is unlikely that you will actually get nanosecond precision from any current machine.

The machine can't create precision, and displaying significant digits where not appropriate is not The Right Thing To Do.

janm
  • 17,976
  • 1
  • 43
  • 61
4

I don't think there's a platform-independent way (maybe some third party has coded one, but I can't find it) to get time in nanoseconds; you need to do it in a platform-specific way. For example, this SO question's answer shows how to do it on platform that supply a librt.so system library for "realtime" operations.

Community
  • 1
  • 1
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395