pandas用BDay计算前一工作日后转换Timestamp为datetime报错如何解决
报错原因
你执行 today - BDay(1) 得到的返回值是 pandas.Timestamp 类型,不是Unix时间戳整数,也不是Python原生datetime对象。而datetime.fromtimestamp()方法只接受秒级Unix时间戳的数值类型入参,传入Timestamp对象就会触发类型不匹配的报错。
可行解决方法
- 方案1(最简洁):直接调用Timestamp对象自带的
strftime方法格式化,无需额外转换类型
修正后完整代码:from pandas.tseries.offsets import BDay from datetime import datetime today = datetime.today() todayminus1 = (today - BDay(1)) todayminus1 = todayminus1.strftime('%d-%m-%y') print("todayminus1 =", todayminus1) - 方案2:先将Timestamp转为Python原生datetime对象后再格式化
核心转换代码:# 调用to_pydatetime()方法转原生datetime todayminus1 = todayminus1.to_pydatetime().strftime('%d-%m-%y') - 方案3:若坚持使用
datetime.fromtimestamp(),先提取Timestamp对应的Unix时间戳数值
核心转换代码:# 先调用timestamp()方法获取秒级时间戳数值 todayminus1 = datetime.fromtimestamp(todayminus1.timestamp()).strftime('%d-%m-%y')
内容的提问来源于stack exchange,提问作者George Boast
相关产品推荐
相关产品推荐

