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


当前回答

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

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

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

其他回答

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

对于Python 3.7+, time.time_ns()给出自epoch以来以纳秒为单位经过的时间。

这给出了以毫秒为单位的整数时间:

import time

ms = time.time_ns() // 1_000_000

在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.")

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

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

使用time.time ():

import time

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

然后:

>>> current_milli_time()
1378761833768