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

如何对pandas DataFrame中datetime.time类型列值求和

问题说明

当前DataFrame结构如下,B列存储datetime.time类型的时分秒值:

A         B
0 x  00:11:12
1 y  00:10:10
2 z  00:00:15
3 g  00:01:32

直接调用df['B'].sum()会抛出TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.time'错误,原因是datetime.time代表时刻点,本身不支持加法运算。
直接执行pd.to_timedelta(df["B"])转换类型会抛出ValueError: Invalid type for timedelta scalar: <class 'datetime.time'>,因为pandas的timedelta转换方法不支持直接接收datetime.time类型作为输入。

解决方法

先把B列的time类型值转为字符串,再转换为支持累加的timedelta类型后求和即可:

# 转换类型后求和
time_sum = pd.to_timedelta(df['B'].astype(str)).sum()

执行后得到的time_sum值为Timedelta('0 days 00:23:09'),和预期结果一致。
如果需要输出纯HH:MM:SS格式的结果,可以通过总秒数换算格式化:

total_seconds = int(time_sum.total_seconds())
hours, remainder = divmod(total_seconds, 3600)
minutes, seconds = divmod(remainder, 60)
formatted_result = f"{hours:02d}:{minutes:02d}:{seconds:02d}"
# formatted_result 值为 '00:23:09'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 09:18:28