如何在Python中获得以毫秒为单位的当前时间?


当前回答

另一个解决方案是可以嵌入到您自己的utils.py中的函数

import time as time_ #make sure we don't override time
def millis():
    return int(round(time_.time() * 1000))

其他回答

只是Python 3+使用datetime模块的另一个解决方案。

时间到了,时间到了,时间到了。

更新:感谢@neuralmer。

最有效的方法之一:

(time.time_ns() + 500000) // 1000000  #rounding last digit (1ms digit)

or

time.time_ns() // 1000000          #flooring last digit (1ms digit)

在其他方法中,这两种方法都非常有效。

基准:

你可以在我自己的机器上看到一些不同方法的基准测试结果:

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

Time.time()可能只给出秒的分辨率,毫秒的首选方法是datetime。

from datetime import datetime
dt = datetime.now()
dt.microsecond

使用time.time ():

import time

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

然后:

>>> current_milli_time()
1378761833768

另一个解决方案是可以嵌入到您自己的utils.py中的函数

import time as time_ #make sure we don't override time
def millis():
    return int(round(time_.time() * 1000))