You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 00:54:05