如何将Python DateTime字符串转换为毫秒整数?
在本文中,我们将讨论在Python中将Python datetime字符串转换为毫秒的各种方法。
使用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: 1662373873162
使用datetime模块
在这里,我们使用datetime模块提供的各种函数来查找当前时间并将此字符串转换为毫秒整数。
首先,我们使用datetime.utcnow()方法检索当前日期。然后,我们通过从当前日期减去日期1970-01-01(datetime(1970, 1, 1))来获得自纪元以来的天数。对于此日期,我们应用.total_seconds()返回自纪元以来的总秒数。最后,我们使用round()函数将值四舍五入到毫秒。
示例1
在下面的示例代码中,我们获取以字符串形式表示的当前时间,并将其转换为毫秒整数。
from datetime import datetime
print("Current date in string format:",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 in string format: 2022-09-05 10:31:52.853660 Number of days since epoch: 19240 days, 10:31:52.853671 Milliseconds since epoch: 1662373912854
示例2
timestamp()函数用于将datetime对象转换为毫秒:
import time from datetime import datetime dt = datetime(2018, 1, 1) milliseconds = int(round(dt.timestamp() * 1000)) print(milliseconds)
输出
这将给出以下输出
1514745000000
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP