datetime – Get current time in milliseconds in Python?

The Question :

573 people think this question is useful

How can I get the current time in milliseconds in Python?

The Question Comments :

The Answer 1

785 people think this answer is useful

For what I needed, here’s what I did, based on @samplebias’ comment above:

import time
millis = int(round(time.time() * 1000))
print millis

Quick’n’easy. Thanks all, sorry for the brain fart.

For reuse:

import time

current_milli_time = lambda: int(round(time.time() * 1000))

Then:

>>> current_milli_time()
1378761833768

The Answer 2

92 people think this answer is useful

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

The Answer 3

56 people think this answer is useful

From version 3.7 you can use time.time_ns() to get time as passed nano seconds from epoch. So you can do

ms = time.time_ns() // 1000000 

to get time in mili-seconds as integer.

The Answer 4

51 people think this answer is useful
def TimestampMillisec64():
    return int((datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1)).total_seconds() * 1000) 

The Answer 5

26 people think this answer is useful

Just sample code:

import time
timestamp = int(time.time()*1000.0)

Output: 1534343781311

The Answer 6

13 people think this answer is useful

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))

The Answer 7

12 people think this answer is useful

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

The Answer 8

9 people think this answer is useful

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.

The Answer 9

9 people think this answer is useful

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

The Answer 10

7 people think this answer is useful

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()

The Answer 11

3 people think this answer is useful

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.

The Answer 12

1 people think this answer is useful

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.

The Answer 13

0 people think this answer is useful

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

The Answer 14

0 people think this answer is useful

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 1000 to get your milliseconds:

start = time.perf_counter_ns()
# do some work
duration = time.perf_counter_ns() - start
print(f"Your duration was {duration // 1000}ms.")

The Answer 15

0 people think this answer is useful

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

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

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 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 1000 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.") #1 ms == 1000000 ns

The Answer 16

-2 people think this answer is useful

Just another solution using the datetime module for Python 3.

int(datetime.datetime.timestamp(datetime.datetime.now()) * 1000)

Add a Comment