36

How can I get the number of milliseconds since epoch?

Note that I want the actual milliseconds, not seconds multiplied by 1000. I am comparing times for stuff that takes less than a second and need millisecond accuracy. (I have looked at lots of answers and they all seem to have a *1000)

I am comparing a time that I get in a POST request to the end time on the server. I just need the two times to be in the same format, whatever that is. I figured unix time would work since Javascript has a function to get that

OrangeDog
  • 36,653
  • 12
  • 122
  • 207
user984003
  • 28,050
  • 64
  • 189
  • 285
  • If you need millisecond accuracy are you sure you need absolute time (since epoch)? Typically that accuracy is only needed in a relative sense, say relative to when the computer started. – Thomas Aug 11 '13 at 05:41
  • 2
    I am comparing a time that I get in a post request to the end time on the server. Really I just need the two times to be in the same format, whatever that is. I figured unix time would work since js has a function to get that. – user984003 Aug 11 '13 at 05:42
  • you probably want [`time.perf_counter()`](https://docs.python.org/3/library/time.html#time.perf_counter) (only relative values make sense) to measure short intervals instead of the absolute time such as provided by `time.time()`. – jfs Apr 24 '15 at 20:36

6 Answers6

30

time.time() * 1000 will give you millisecond accuracy if possible.

20

int(time.time() * 1000) will do what you want. time.time() generally returns a float value with double precision counting seconds since epoche, so multiplying it does no harm to the precision.

Another word to the misleading answer of @kqr: time.clock() does not give you the time of the epoch. It gives you the time that the process ran on the CPU for Unix, or the time passed since the first call to the function on Windows, see the python docs.

Also it's true that the docs state, that time.time() is not guaranteed to give you ms precision. Though this statement is mainly ment for you to make sure not to rely on this precision on embedded or praehistoric hardware, and I'm not aware of any example, where you actually wouldn't get ms precision.

Michael
  • 7,316
  • 1
  • 37
  • 63
15

I see many people suggesting time.time(). While time.time() is an accurate way of measuring the actual time of day, it is not guaranteed to give you millisecond precision! From the documentation:

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.

This is not the procedure you want when comparing two times! It can blow up in so many interesting ways without you being able to tell what happened. In fact, when comparing two times, you don't really need to know what time of day it is, only that the two values have the same starting point. For this, the time library gives you another procedure: time.clock(). The documentation says:

On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name, but in any case, this is the function to use for benchmarking Python or timing algorithms.

On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.

Use time.clock().


Or if you just want to test how fast your code is running, you could make it convenient for yourself and use timeit.timeit() which does all of the measuring for you and is the de facto standard way of measuring elapsed time in code execution.

kqr
  • 14,791
  • 3
  • 41
  • 72
  • 2
    So on Unix, `clock()` is *not* appropriate. It counts, as you cite, processor time which is different from wall clock time, even in relative manners. – glglgl Aug 11 '13 at 09:24
  • 1
    If you are simply comparing two times, calculating the difference between two `clock()` calls will give you the most accurate measure of passed time. Using `time()` the delta might not be precise enough, and could even be *negative*! – kqr Aug 11 '13 at 09:49
  • 2
    If you have several programs running at the same time, your system gets slower. The programs need more wall clock time, but the same CPU time. That can be a huge difference if you need the precise time. – glglgl Aug 11 '13 at 10:00
  • Using `time()` can be a problem if the system time is adjusted abruptly by a huge amount. That's why e. g. NTP slowly adjusts the time frequency instead of abruptly setting the time to a different value. – glglgl Aug 11 '13 at 10:02
  • @glglgl The Python `clock()` method depends on the underlying C `clock()` function, which has a fixed tick rate `CLOCKS_PER_SEC`. Unless I have missed something, the tick speed should *not* vary with time. – kqr Aug 11 '13 at 10:12
  • 4
    [This program](http://pastebin.com/0fcygeBF) shows the difference. If I run it to the end, the last calls to `fac()` need a CPU time of about .58 s, but a real time of about 7.5 s. This is because they don't get the full CPU's attention, and a job which ought to be finished in .58 s needs 7.5 s due to parallelization. – glglgl Aug 11 '13 at 10:33
  • Interesting. I didn't really consider parallelisation as a factor in this. It seems like you are right. – kqr Aug 11 '13 at 11:09
  • 2
    If you're going to place the result in a DB, but sure to convert to str first as Python will note the long integer with a trailing "L". Typical Python stuff, but I got burned by it today.... – ChronoFish Dec 29 '14 at 01:17
  • 1
    The question specifically states 'milliseconds since the epoch'. `>>> import time¶ >>> time.clock()¶ 0.012488` Hey! Wow! It's 1 January 1970! Wait—that means I haven't been born yet! _::poof::_ Aw. Rats. – Michael Scheper Dec 02 '15 at 23:32
  • 1
    @MichaelScheper Don't get too stuck on the "epoch" part – focus more on the "compare two times", "millisecond" and "benchmarking" aspects of the question. http://xyproblem.info/ :) – kqr Dec 03 '15 at 10:05
  • 1
    @kqr: I'm sorry, but it's not for you to judge what I get 'stuck on'. I landed here by doing a websearch, because I need to know the time since the epoch, or at least some other consistent reference time. The body of the question mentions the epoch right in the first sentence, so it's a reasonable point of 'focus'. My code failed when I tried using `time.clock()`, because I'm comparing times from different processes, and `time.clock()` is apparently process-specific. Your answer may be helpful for some, but it does accurately answer the question, so please edit it to clarify it. – Michael Scheper Dec 03 '15 at 22:18
  • 1
    This answer is plain wrong, especially in a multithreaded context, and should simply be downvoted. – Michael Jan 03 '17 at 08:51
  • Regarding the python documentation, I always have wondered *which* systems don't have sub-second resolution for time.time(). Like, which particular ones don't, so I can watch out for them. – Jacob Lee Aug 20 '18 at 21:47
14

Using datetime:

>>> import datetime
>>> delta = datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1)
>>> delta
datetime.timedelta(15928, 52912, 55000)
>>> delta.total_seconds()
1376232112.055
>>> delta.days, delta.seconds, delta.microseconds
(15928, 52912, 55000)
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • 3
    it is incorrect unless the current UTC offset is exactly the same as in 1970. Use `.utcnow()`. [more](http://stackoverflow.com/q/26313520/4279) – jfs Aug 22 '16 at 10:33
2

Python 3.7 introduced time.time_ns() to finally solve this problem since time.time() as mentioned is not useful for this.

"returns time as an integer number of nanoseconds since the epoch."

https://www.python.org/dev/peps/pep-0564/
https://docs.python.org/3/library/time.html#time.time_ns

user136036
  • 11,228
  • 6
  • 46
  • 46
-4
import datetime
time = datetime.datetime.now()
ms = time.microsecond

Returns a 6 digit number, microsecond. The last 3 digits are useless in PC since it works with ticks, which is slower than microsecond. The first 3 digits should be enough for your need.

Sharon Dorot
  • 542
  • 1
  • 4
  • 15
  • 2
    "Useless in PC since it works with ticks, which is slower than microsecond". Interesting. – Hyperboreus Aug 11 '13 at 07:28
  • 4
    That won't give you milliseconds since the epoche, but milliseconds since the last second start. – Michael Aug 11 '13 at 07:34
  • I was curious why I'm seeing the spelling 'epoche' so much on this page. A Google search says 'Epoche is a lovely gift store in Kallista, Victoria'—probably not what people mean. There's Epoché, an ancient Greek term, which is probably the source of the modern English word 'epoch'. But in every dictionary I've checked, 'epoch' is the correct spelling... unless 'epoche' is another one of those 'US English' spellings... – Michael Scheper Dec 02 '15 at 23:26
  • 1
    @MichaelScheper Only if you count incidental misspellings as American English. Since both instances on this page are from the same user, we can assume that he is either mistaken or deliberately taking it back to the Greek source. – Hobbes Feb 04 '16 at 23:02