Pandas字符串转Epoch时间戳报错,如何正确转换并计算时间差?
将ISO时间字符串转换为Epoch时间并计算时间差
你的代码错误在于给pd.to_datetime()传入了unit='s'参数——这个参数是用来告诉pandas“输入的是秒级Epoch数值”,但你的evt_time是标准ISO 8601格式的字符串,不需要这个参数。
要把evt_time转换成和time.time()一致的Epoch时间(秒级浮点数),有两种常用方法:
方法一:使用Pandas
import time import pandas as pd now = time.time() evt_time = '2022-10-20T04:10:36Z' # 直接解析ISO时间字符串为datetime对象 evt_datetime = pd.to_datetime(evt_time) # 转换为Epoch时间(秒级) evt_epoch = evt_datetime.timestamp() # 计算时间差(单位:秒) diff_time = now - evt_epoch
pd.to_datetime()可以直接识别Z结尾的UTC时间字符串,无需额外处理。timestamp()方法会返回从1970-01-01 00:00:00 UTC到该时间的秒数,和time.time()的输出格式完全匹配。
方法二:使用Python标准库(无需Pandas)
如果不想依赖Pandas,用datetime标准库也能实现:
import time from datetime import datetime now = time.time() evt_time = '2022-10-20T04:10:36Z' # 将Z替换为+00:00,让fromisoformat正确识别UTC时间 evt_datetime = datetime.fromisoformat(evt_time.replace('Z', '+00:00')) # 转换为Epoch时间 evt_epoch = evt_datetime.timestamp() # 计算时间差 diff_time = now - evt_epoch
两种方法最终都能得到正确的diff_time,结果是两个时间点之间的秒数差。
内容的提问来源于stack exchange,提问作者FlyingPickle
相关产品推荐
相关产品推荐

