如何将日期时间字符串转换为毫秒 UNIX 时间戳?
可以使用 time 模块以毫秒为单位获取当前时间。可以使用 time.time 函数以秒为单位获取时间(作为浮点值)。要将其转换为毫秒,需要将其乘以 1000 并四舍五入。
示例
import time milliseconds = int(round(time.time() * 1000)) print(milliseconds)
输出
这将给出以下输出 −
1514825676008
如果你想将 datetime 对象转换为毫秒时间戳,可以使用 timestamp 函数,然后应用上述相同的数学运算获得毫秒时间。
Learn Linux/Unix in-depth with real-world projects through our Linux/Unix certification course. Enroll and become a certified expert to boost your career.
示例
import time from datetime import datetime dt = datetime(2018, 1, 1) milliseconds = int(round(dt.timestamp() * 1000)) print(milliseconds)
输出
这将给出以下输出 −
1514745000000
广告