如何在Python中获取当前时间的毫秒数?
在本文中,我们将讨论Python中检索当前时间毫秒的各种方法。
阅读更多:Python 教程
使用time.time()方法
Python中的time模块提供了与时间相关的各种方法和函数。在这里,我们使用time.time()方法获取当前CPU时间(以秒为单位)。时间从纪元计算。它返回一个以秒为单位表示的浮点数。然后,将此值乘以1000,并使用 round() 函数四舍五入。
注意 :纪元是时间的起始点,具体取决于平台。纪元是1970年1月1日00:00:00(UTC)在Windows和大多数Unix系统上,闰秒未包括在自纪元起算的秒数中。
我们使用time.gmtime(0)在给定平台上获取原点。
语法
time() 方法的语法如下所示−
time.time()
返回一个表示自纪元以来的秒数的浮点值。
示例
在以下示例代码中,我们使用time.time()方法获取当前时间(以秒为单位)。然后我们乘以1000,使用round()函数近似值。
import time
obj = time.gmtime(0)
epoch = time.asctime(obj)
print("The epoch is:",epoch)
curr_time = round(time.time()*1000)
print("Milliseconds since epoch:",curr_time)
输出
以上代码的输出如下;
The epoch is: Thu Jan 1 00:00:00 1970
Milliseconds since epoch: 1662372570512
使用datetime模块
在这里,我们使用datetime模块提供的各种函数来找到当前的毫秒数。
最初,我们使用datetime.utc()方法检索当前日期。然后,我们通过从当前日期中减去01-01-1670(datetime(1970,1,1))来获取自纪元以来的天数。对于这个日期,我们应用.total_seconds()返回自纪元以来的总秒数。最后,我们使用round()函数将该值四舍五入为毫秒。
示例
在以下示例代码中,我们使用Python datetime模块提供的不同函数获取当前的毫秒数。
from datetime import datetime
print("Current date:",datetime.utcnow())
date= datetime.utcnow() - datetime(1970, 1, 1)print("Number of days since epoch:",date)
seconds =(date.total_seconds())
milliseconds = round(seconds*1000)
print("Milliseconds since epoch:",milliseconds)
输出
上述示例代码的输出如下;
Current date: 2022-09-05 10:10:17.745855
Number of days since epoch: 19240 days, 10:10:17.745867
Milliseconds since epoch: 1662372617746