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

如何在Pandas DataFrame中将timedelta转换为整数?

将Pandas Timedelta转换为整数的正确方法

问题原因

pd.to_numeric 不支持直接转换 Timedelta 对象,这就是你遇到 TypeError: Invalid object type at position 0 的原因——该函数仅能处理字符串、数值型等可直接转为数字的类型,无法解析时间差对象。

解决办法

根据你需要的时间单位,选择以下方式:

  • 提取天数为整数
    直接访问 Timedelta 对象的 .days 属性:

    time = pd.to_datetime(each_date2) - pd.to_datetime(each_date1)
    days_integer = time.days  # 结果为7
    
  • 提取总秒数为整数
    如果需要包含天、时、分、秒的总时长,用 .total_seconds() 方法后转整数:

    total_seconds = int(time.total_seconds())  # 结果为604800
    
  • 处理TimedeltaSeries(批量时间差)
    如果你的 time 是一个Series,使用 .dt 访问器提取属性:

    # 示例:批量转换
    td_series = pd.Series([pd.Timedelta('7 days'), pd.Timedelta('12 hours')])
    # 转天数整数
    day_int_series = td_series.dt.days
    # 转总秒数整数
    sec_int_series = td_series.dt.total_seconds().astype(int)
    

内容的提问来源于stack exchange,提问作者mona

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 10:52:03