How do I get the current time in milliseconds in Python?
-
84`import time; ms = time.time()*1000.0` – samplebias May 13 '11 at 22:07
-
4@samplebias: `time.time()` may provide worse precision than `datetime.utcnow()` on some platforms and python versions. – jfs Mar 24 '15 at 20:20
-
7In milliseconds since _when_? If you mean since the epoch (midnight 1 January 1970 UTC), see this: http://stackoverflow.com/questions/18169099/python-get-milliseconds-since-epoch-millisecond-accuracy-not-seconds1000 – Michael Scheper Dec 02 '15 at 23:20
-
2For true microsecond-resolution milliseconds time stamps see here: http://stackoverflow.com/questions/38319606/how-to-get-millisecond-and-microsecond-resolution-timestamps-in-python – Gabriel Staples Jul 12 '16 at 04:40
16 Answers
Using time.time()
:
import time
def current_milli_time():
return round(time.time() * 1000)
Then:
>>> current_milli_time()
1378761833768

- 14,854
- 11
- 100
- 103

- 87,710
- 93
- 269
- 411
-
62This may not give the correct answer. According to the docs, "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" – Jason Polites Nov 02 '12 at 17:21
-
20I am wondering, why do you need to `round`? It seems `int(time.time() * 1000)` is enough? – Maxim Vladimirsky Jun 13 '13 at 17:08
-
22IMO I'd use floor and not round, but that's just me. If someone asks what the hour is, and it's 7:32, the number they probably want is 7, not 8. – davr Sep 09 '13 at 20:37
-
As posted in answers below, under windows `datetime.now()` or `time.time()` resolution will be several **milliseconds**. For better resolution, you should combine `now()` with the use of `time.clock()`, which captures the high-performance counters of the OS, yielding **uSec** resolution. – Parallel Universe Dec 28 '14 at 18:56
-
1@ParallelUniverse: [`.utcnow()` uses `GetSystemTimeAsFileTime()` on recent CPython on Windows](http://stackoverflow.com/a/28574340/4279). Wouldn't `time.clock()` call (`QueryPerformanceCounter()`) introduce more noise than it might reduce? See [Precision is not the same as accuracy](http://blogs.msdn.com/b/oldnewthing/archive/2005/09/02/459952.aspx). – jfs Apr 24 '15 at 20:47
-
The lambda approach rocks as hell. Got to look this operator a little bit more deeper, thanks @NaftuliTzviKay – ferdy Jun 13 '15 at 15:41
-
Seems to be good to at least 1/100th of a second in Windows 7, so good enough for me. – ArtOfWarfare Jul 20 '15 at 20:36
-
17@MaximVladimirsky That isn't the behavior of int(). Int does not floor a value, it rounds toward zero. Which is the same thing for positive number, but the opposite for negative. int(1.5) gives 1, int(-1.5) gives -1, math.floor(-1.5) gives -2 See: https://docs.python.org/2/library/stdtypes.html – Skip Huffman Jul 30 '15 at 14:24
-
For true microsecond-resolution milliseconds time stamps see here: http://stackoverflow.com/questions/38319606/how-to-get-millisecond-and-microsecond-resolution-timestamps-in-python – Gabriel Staples Jul 12 '16 at 04:41
-
-
1Determining the differences up to microseconds resolution (like benchmarking code) and getting a general time of today (up to milliseconds) are very different requirement, and needs different tools for that. Indeed the realtime clock hardware is only as accurate up to milliseconds resolutions, x86 CPU provides another facility for microseconds stuff. Use time.perf_counter() in python 3 for microseconds purposes. – HelloSam Dec 28 '17 at 03:20
-
@naftuli-kay i see the int vs round (floor vs round) but if you use the round() one do you need to also int(round()) it ? – Yoni Jun 03 '18 at 11:35
-
3@SkipHuffman Since you will never get a negative number for the current time, you can just use `int(time.time() * 1000)`. – EzPizza Nov 05 '20 at 14:15
-
1@AlguemMeugla This isn't about what you would say to another human being, who just needs a rough estimate. If a program needs the precise number of the current hour of day, then you should say 7, even if it is 7:59. – EzPizza Nov 05 '20 at 14:18
-
-
For Python 3.7+, time.time_ns()
gives the time passed in nanoseconds since the epoch.
This gives time in milliseconds as an integer:
import time
ms = time.time_ns() // 1_000_000

- 24,552
- 19
- 101
- 135

- 3,014
- 2
- 24
- 32
-
1@AlexWalterbos Nano: 10^-9 ; Milli: 10^-3 ; Each millisecond is 10^6 nanosecond – zardosht Sep 27 '22 at 17:46
-
@AlexWalterbos Consider editing your wrong comment above, because google thinks it's the right one. Check it out - https://i.imgur.com/O2PNbVu.png – Abraham Tugalov Dec 08 '22 at 10:47
-
3To get the time in milliseconds, `time_ns()` must be divided by 1000000. This comment is a correction of my previous comment (now deleted), to prevent confusion. Thanks to @AbrahamTugalov for the suggestion to clarify. – AlexWalterbos Dec 09 '22 at 11:07
time.time()
may only give resolution to the second, the preferred approach for milliseconds is datetime
.
from datetime import datetime
dt = datetime.now()
dt.microsecond

- 18,571
- 11
- 90
- 141

- 5,571
- 3
- 25
- 24
-
149not quite useful - this only gives you the microseconds **within** the dt's second. see http://stackoverflow.com/a/1905423/74632 – Boris Chervenkov Nov 05 '12 at 00:23
-
9+1 because this is the official way to get a reliable timestamp from the system. – Pascal Feb 20 '13 at 10:54
-
Actually the question is about milliseconds rather than microseconds, which is not so easy – Purrell Feb 25 '15 at 23:56
-
1@Jan: On old CPython versions on some systems, [`datetime.utcnow()` could have provided a better resolution than `time.time()`](http://stackoverflow.com/a/28574340/4279). Though on most systems or in [the current CPython, both `time.time()`](http://stackoverflow.com/a/27835769/4279) and `datetime.utcnow()` use the same underlying OS API to get the time. [@user3324131 shows how to get milliseconds from `datetime.utcnow()`](http://stackoverflow.com/a/21858377/4279). – jfs Apr 18 '15 at 17:36
-
43-1. this is an incorrect answer to this question. as @Boris commented, this does not give "the time in microseconds", e.g. does not include days, hours, seconds in number of microseconds. – j-a Sep 03 '15 at 06:56
-
4+1 This gives a correct value and arithmetic can be assumed to work because math. If the user needs the current time in milliseconds/microseconds, simple arithmetic will get them there. If a time delta is needed--which is not asked for--arithmetic, again, saves the day. – Jack Stout Apr 13 '16 at 18:11
-
@j-a: it is easy to [add microseconds corresponding to days, etc](http://stackoverflow.com/questions/5998245/get-current-time-in-milliseconds-in-python#comment46689980_21858377) – jfs Aug 22 '16 at 10:40
-
1@J.F.Sebastian no it is not. You don't know if one of those days was a day with leap seconds. – j-a Aug 22 '16 at 10:52
-
2@j-a: it does include "days, hours, seconds" (it fixes the issue pointed out in your comment). To address the *new* issue (leap seconds): POSIX time does NOT count leap seconds and `time.time()` returns POSIX time on most systems supported by Python (if we exclude uncommon "right" timezones). Don't confuse precision and accuracy -- this question is about the millisecond precision -- if you need the millisecond accuracy then you need to talk about clock synchronization, ntp (LAN vs. WAN), etc first. – jfs Aug 22 '16 at 11:08
-
1@J.F.Sebastian you are right. The answer would still need to be updated though. – j-a Aug 22 '16 at 12:34
-
8
-
-
-
Can this answer be marked as wrong, as it gives only the microsecond part (ie. time_in_microseconds mod 1000000)? It has a lot of upvotes, which is quite confusing. – user1587520 Nov 11 '21 at 13:40
-
1Answer posts are not reserved for "only those answers that fully solve the problem", they may also be used to post information that's helpful in solving the problem. In this case, the answer clearly demonstrates how to get the most important part required, and it can be assumed that people know how basic arithmetics works in Python to do the rest. If you feel this answer should include the single extra line to do that work: if you have enough rep you can [edit] this post to add that in. At worst, this answer is "incomplete", it is very much not "wrong". – Mike 'Pomax' Kamermans Jan 04 '23 at 20:21
def TimestampMillisec64():
return int((datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1)).total_seconds() * 1000)

- 923
- 8
- 10
-
3you could inline the formula for `.total_seconds()` to produce (possibly) better precision: [`(td.microseconds + (td.seconds + td.days * 86400) * 10**6) / 10**3` (with true division enabled)](http://stackoverflow.com/a/8778548/4279) Or if you want to truncate the milliseconds then use `// 10**3`. – jfs Mar 24 '15 at 20:13
-
1
-
If you are presenting this as a cross platform python solution, is there an assurance that all platforms and all python versions 3+ will properly account for any past leap seconds in what is returned by datetime.datetime.utcnow(), or are there lurking difficulties with this as a consistent cross platform solution? – always_learning Oct 27 '20 at 13:59
Just sample code:
import time
timestamp = int(time.time()*1000.0)
Output: 1534343781311

- 1,790
- 19
- 13
In versions of Python after 3.7, the best answer is to use time.perf_counter_ns()
. As stated in the docs:
time.perf_counter() -> float
Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.
time.perf_counter_ns() -> int
Similar to perf_counter(), but return time as nanoseconds
As it says, this is going to use the best counter your system has to offer, and it is specifically designed for using in measuring performance (and therefore tries to avoid the common pitfalls of other timers).
It also gives you a nice integer number of nanoseconds, so just divide by 1000000 to get your milliseconds:
start = time.perf_counter_ns()
# do some work
duration = time.perf_counter_ns() - start
print(f"Your duration was {duration // 1000000}ms.")

- 2,725
- 2
- 14
- 22

- 5,587
- 2
- 22
- 26
-
1
-
1I don't believe so. Using `time.time_ns()` is your best bet, but it has different guarantees. – Andrew Miner Nov 17 '21 at 21:08
If you want a simple method in your code that returns the milliseconds with datetime:
from datetime import datetime
from datetime import timedelta
start_time = datetime.now()
# returns the elapsed milliseconds since the start of the program
def millis():
dt = datetime.now() - start_time
ms = (dt.days * 24 * 60 * 60 + dt.seconds) * 1000 + dt.microseconds / 1000.0
return ms

- 2,197
- 3
- 24
- 34
-
this is the difference between two times in milliseconds, combining your method with @Jason s answer gives the current timestamp in milliseconds... Thinking about it, the UNIX timestamp would be your method with `start_time` = datetime(1970,1,1) – P.R. Nov 20 '13 at 15:51
-
local time may be ambiguous and non-monotonous (due to DST transitions or other reasons to change the local utc offset). Use `.utcnow()` instead or if you don't need the absolute time then you could use `time.monotonous()`. Note: there is a subtle difference due to floating-point arithmetics between `some_int + dt.microseconds/ 1000.0` and the formula `( ) / 10**3` with true division enabled. See [the explicit formula and the link for `total_seconds()` in the related answer](http://stackoverflow.com/q/8777753/4279) – jfs Mar 24 '15 at 20:10
If you're concerned about measuring elapsed time, you should use the monotonic clock (python 3). This clock is not affected by system clock updates like you would see if an NTP query adjusted your system time, for example.
>>> import time
>>> millis = round(time.monotonic() * 1000)
It provides a reference time in seconds that can be used to compare later to measure elapsed time.

- 12,780
- 1
- 26
- 30
another solution is the function you can embed into your own utils.py
import time as time_ #make sure we don't override time
def millis():
return int(round(time_.time() * 1000))

- 24,725
- 16
- 62
- 87

- 199
- 1
- 4
-
[@Cadey][1] this solution is dangerous, it will give you back results which have different sizes eg. 13 characters normally but sometimes it turns the result to a timestamp which follows seconds and not milis, if you use the dates to compare you will run into issues (experiences this on our production system, replicated this using a python script) – Oliver Jun 27 '23 at 05:11
The simpliest way I've found to get the current UTC time in milliseconds is:
# timeutil.py
import datetime
def get_epochtime_ms():
return round(datetime.datetime.utcnow().timestamp() * 1000)
# sample.py
import timeutil
timeutil.get_epochtime_ms()

- 1,450
- 18
- 25
If you use my code (below), the time will appear in seconds, then, after a decimal, milliseconds. I think that there is a difference between Windows and Unix - please comment if there is.
from time import time
x = time()
print(x)
my result (on Windows) was:
1576095264.2682993
EDIT: There is no difference:) Thanks tc0nn

- 526
- 7
- 21
-
1No diff on Mac OSX:`/usr/local/opt/python/bin/python3.7 scratch.py 1577212639.882543` – tc0nn Dec 24 '19 at 18:37
-
1
UPDATED: thanks to @neuralmer.
One of the most efficient ways:
(time.time_ns() + 500000) // 1000000 #rounding last digit (1ms digit)
or
time.time_ns() // 1000000 #flooring last digit (1ms digit)
Both are very efficient among other methods.
BENCHMARK:
You can see some benchmark results of different methods on my own machine below:
import time
t = time.perf_counter_ns()
for i in range(1000):
o = time.time_ns() // 1000000 #each 200 ns
t2 = time.perf_counter_ns()
print((t2 - t)//1000)
t = time.perf_counter_ns()
for i in range(1000):
o = (time.time_ns() + 500000) // 1000000 #each 227 ns
t2 = time.perf_counter_ns()
print((t2 - t)//1000)
t = time.perf_counter_ns()
for i in range(1000):
o = round(time.time_ns() / 1000000) #each 456 ns
t2 = time.perf_counter_ns()
print((t2 - t)//1000)
t = time.perf_counter_ns()
for i in range(1000):
o = int(time.time_ns() / 1000000) #each 467 ns
t2 = time.perf_counter_ns()
print((t2 - t)//1000)
t = time.perf_counter_ns()
for i in range(1000):
o = int(time.time()* 1000) #each 319 ns
t2 = time.perf_counter_ns()
print((t2 - t)//1000)
t = time.perf_counter_ns()
for i in range(1000):
o = round(time.time()* 1000) #each 342 ns
t2 = time.perf_counter_ns()
print((t2 - t)//1000)```

- 1,832
- 1
- 20
- 35
-
1OP is looking for milliseconds, by dividing by only 1000, you're providing microseconds. (milli-, micro-, nano-) – neuralmer Aug 19 '21 at 15:36
-
After some testing in Python 3.8+ I noticed that those options give the exact same result, at least in Windows 10.
import time
# Option 1
unix_time_ms_1 = int(time.time_ns() / 1000000)
# Option 2
unix_time_ms_2 = int(time.time() * 1000)
Feel free to use the one you like better and I do not see any need for a more complicated solution then this.

- 24,552
- 41
- 131
- 206

- 121
- 1
- 8
These multiplications to 1000 for milliseconds may be decent for solving or making some prerequisite acceptable. It could be used to fill a gap in your database which doesn't really ever use it. Although, for real situations which require precise timing it would ultimately fail. I wouldn't suggest anyone use this method for mission-critical operations which require actions, or processing at specific timings.
For example: round-trip pings being 30-80ms in the USA... You couldn't just round that up and use it efficiently.
My own example requires tasks at every second which means if I rounded up after the first tasks responded I would still incur the processing time multiplied every main loop cycle. This ended up being a total function call every 60 seconds. that's ~1440 a day.. not too accurate.
Just a thought for people looking for more accurate reasoning beyond solving a database gap which never really uses it.

- 5,738
- 6
- 35
- 54

- 51
- 2
-
3Do you have a better solution? Also honestly, I don't get what you are saying at all. What do you mean by "round up"? – Imperishable Night Jun 17 '19 at 03:36
-
3Explain your solution with a practical example for better understanding – Ratan Uday Kumar Jun 17 '19 at 03:39
Time since unix
from time import time
while True:
print(str(time()*1000)+'ms \r', end='')
Time since start of program
from time import time
init = time()
while True:
print(str((time()-init)*1000)+'ms \r', end='')
Thanks for your time

- 627
- 4
- 15
Just another solution using the datetime
module for Python 3+.
round(datetime.datetime.timestamp(datetime.datetime.now()) * 1000)

- 1,900
- 1
- 19
- 20