如何在 Python 中获取当前时间(以毫秒为单位)?
在本文中,我们将讨论在 Python 中检索当前时间(以毫秒为单位)的各种方法。
使用 time.time() 方法
Python 中的 time 模块提供了各种与时间相关的函数和方法。这里我们使用 time.time() 方法 来获取当前 CPU 时间(以秒为单位)。时间是从纪元开始计算的。它返回一个以秒表示的浮点数。然后,此值乘以 1000,并使用 round() 函数 四舍五入。
注意:纪元是时间的起点,并且依赖于平台。在 Windows 和大多数 Unix 系统上,纪元是 1970 年 1 月 1 日 00:00:00(UTC),并且自纪元以来的时间(以秒为单位)中不包括闰秒。
我们使用 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() 方法检索当前日期。然后,我们通过从当前日期减去 1970-01-01(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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP