Get current time in milliseconds in Python?

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


Solution 1:

Using time.time():

import time

def current_milli_time():
    return round(time.time() * 1000)

Then:

>>> current_milli_time()
1378761833768

Solution 2:

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() // 1_000_000 

to get time in mili-seconds as integer.

Solution 3:

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

Solution 4:

def TimestampMillisec64():
    return int((datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1)).total_seconds() * 1000)