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


当前回答

如果你关心测量流逝的时间,你应该使用单调时钟(python 3)。例如,如果一个NTP查询调整了你的系统时间,这个时钟不会受到系统时钟更新的影响。

>>> import time
>>> millis = round(time.monotonic() * 1000)

它提供了一个以秒为单位的参考时间,可用于以后比较以测量经过的时间。

其他回答

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

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

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

使用time.time ():

import time

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

然后:

>>> current_milli_time()
1378761833768

在3.7之后的Python版本中,最好的答案是使用time.perf_counter_ns()。如文件所述:

Time.perf_counter() ->浮点数

返回性能计数器的值(以小数秒为单位),即具有最高可用分辨率的时钟,用于测量短时间。它确实包括睡眠期间所消耗的时间,并且是系统范围的。返回值的参考点未定义,因此只有连续调用结果之间的差值才是有效的。

Time.perf_counter_ns () -> int

类似于perf_counter(),但是返回以纳秒为单位的时间

正如它所说,这将使用您的系统所提供的最佳计数器,并且它是专门为测量性能而设计的(因此试图避免其他计时器的常见陷阱)。

它也给了你一个很好的纳秒整数,所以只要除以1000000就得到你的毫秒:

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

如果你想在你的代码中使用一个简单的方法,用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