TypeError修复:不降级Python版本解决Decimal转时间戳报错问题
解决Decimal转datetime的TypeError问题
报错根源
datetime.utcfromtimestamp() 仅支持Python原生数值类型(int/float),无法直接解析decimal.Decimal对象,因此抛出类型错误。
修复方案1:显式转换Decimal为float(修改原有apply逻辑)
在lambda表达式中先将Decimal对象转为float,再传入utcfromtimestamp:
from datetime import datetime df['sample_time'] = df['sample_time'].apply(lambda x: datetime.utcfromtimestamp(float(x) / 1000).strftime('%Y-%m-%d %H:%M:%S'))
注意:原代码中的
%D是月/日/年格式(如06/15/24),若需要年-月-日格式,需改为%d,即%Y-%m-%d %H:%M:%S。
修复方案2:使用pandas原生方法(更高效)
对于DataFrame批量处理,pandas内置的to_datetime性能远优于apply,推荐使用:
import pandas as pd # 将Decimal转为float后,指定unit='ms'处理毫秒级时间戳 df['sample_time'] = pd.to_datetime(df['sample_time'].astype(float), unit='ms').dt.strftime('%Y-%m-%d %H:%M:%S')
额外提示
如果你的时间戳是整数毫秒,也可以先转int再计算:int(x)/1000,结果与转float一致。以上方案均兼容Python3.7及以上受支持版本,无需降级。
内容的提问来源于stack exchange,提问作者Christopher McHugh
相关产品推荐
相关产品推荐

