How do I get the current time in milliseconds in Python?
19 Answers
Using time.time():
import time
def current_milli_time():
return round(time.time() * 1000)
Then:
>>> current_milli_time()
1378761833768
16 Comments
round? It seems int(time.time() * 1000) is enough?int(time.time() * 1000).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
2 Comments
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
16 Comments
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.def TimestampMillisec64():
return int((datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1)).total_seconds() * 1000)
3 Comments
.total_seconds() to produce (possibly) better precision: (td.microseconds + (td.seconds + td.days * 86400) * 10**6) / 10**3 (with true division enabled) Or if you want to truncate the milliseconds then use // 10**3.Just sample code:
import time
timestamp = int(time.time()*1000.0)
Output: 1534343781311
1 Comment
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 Comments
time.time_ns() is your best bet, but it has different guarantees.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
4 Comments
start_time = datetime(1970,1,1).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.utcnow() is deprecated in 3.12time.time_ns() and time.perf_counter_ns() for small relative case correspondinglyIf 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.
Comments
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))
1 Comment
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
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)```
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.
Comments
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.
2 Comments
In typical Linux and Windows, time.time_ns() // 1_000_000 is cheaper than round(time.time() * 1000):
import time
def benchmark_time_time():
start = time.time()
for _ in range(10_000_000):
round(time.time() * 1000)
end = time.time()
return end - start
def benchmark_time_time_ns():
start = time.time()
for _ in range(10_000_000):
time.time_ns() // 1_000_000
end = time.time()
return end - start
time_time_duration = benchmark_time_time()
time_time_ns_duration = benchmark_time_time_ns()
print(time_time_duration)
print(time_time_ns_duration)
print(time_time_duration/time_time_ns_duration * 100 - 100)
It seems that round(time.time() * 1000) takes roughly 20~60% more time in Linuxes and ~100% in Windows, just roughly saying.
Comments
If you were already using pandas library, then you can view the current timestamp (in local time by default but the timezone can be changed) as nanoseconds since the UNIX epoch (using view()). Then to convert the nanoseconds into milliseconds resolution, divide the value by 1000000.
# for a single timestamp
pd.Timestamp('now').asm8.view('int64') // 10**6
# if a column (which is probably more common)
pd.Series([pd.Timestamp('now')]).view('int64') // 10**6
If you were using the numpy library, then numpy has datetime64 function where you can specify the resolution (ms in this case) and view it as int64. Note that unlike pandas, it's UTC time.
np.datetime64('now', 'ms').view('int64')
Comments
The datetime documentation show that timedelta implements maths operator
The code to copy:
from datetime import datetime, timedelta
current_time_float_millisecond = (datetime.now() - datetime.fromtimestamp(0)) / timedelta(0, 0, 1000)
here a python session step by step to show how we construct the formula:
Python 3.11.9 (main, Aug 13 2024, 02:18:20) [GCC 12.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime, timedelta
>>> current_time = datetime.now()
>>> current_time
datetime.datetime(2024, 8, 28, 12, 40, 50, 631009)
>>> datetime.fromtimestamp(0)
datetime.datetime(1970, 1, 1, 0, 0)
>>> timedelta(0, 0, 1000)
datetime.timedelta(microseconds=1000)
>>> current_time - datetime.fromtimestamp(0)
datetime.timedelta(days=19963, seconds=45650, microseconds=631009)
>>> (current_time - datetime.fromtimestamp(0)) / timedelta(0, 0, 1000)
1724848850631.009
>>> (19963*24*60*60+45650) * 1000 + 631009 / 1000
1724848850631.009
This solution was not posted (but multiple answer propose time.time() * 1000). It highlight the python type timedelta that allow to customize the formula easily for various unit (datetime.timedelta(microseconds=1) for μs)
import time; ms = time.time()*1000.0time.time()may provide worse precision thandatetime.utcnow()on some platforms and python versions.