Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current time in milliseconds in Python?

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

like image 263
Naftuli Kay Avatar asked May 13 '11 22:05

Naftuli Kay


People also ask

How do I get the current millisecond in Python?

You can get the current time in milliseconds in Python using the time module. You can get the time in seconds using time. time function(as a floating point value). To convert it to milliseconds, you need to multiply it with 1000 and round it off.

How do I get the current time in Python?

Python Current Date Time in timezone - pytzPython datetime now() function accepts timezone argument that should be an implementation of tzinfo abstract base class. Python pytz is one of the popular module that can be used to get the timezone implementations. You can install this module using the following PIP command.


3 Answers

Using time.time():

import time

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

Then:

>>> current_milli_time()
1378761833768
like image 183
Naftuli Kay Avatar answered Oct 19 '22 16:10

Naftuli Kay


For Python 3.7+, use time.time_ns() to get time as passed nanoseconds from epoch.

This gives time in milliseconds as an integer:

import time

ms = time.time_ns() // 1_000_000
like image 136
zardosht Avatar answered Oct 19 '22 16:10

zardosht


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
like image 95
Jason Polites Avatar answered Oct 19 '22 15:10

Jason Polites