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

如何对pandas DataFrame中时分秒格式的时间数据执行求和运算

针对pandas中时分秒格式时间列的求和方案

核心逻辑是把%H:%M:%S格式的字符串转为pandas内置的timedelta时间差类型,该原生类型支持直接求和运算,处理百万级以上的数据量也不会有性能问题。

步骤1:转换时间列格式

使用pd.to_timedelta直接把字符串列转为时间差类型:

import pandas as pd

# 转换列,errors='coerce'可自动把非法格式的值转为空时间值NaT,避免报错
df['time_col'] = pd.to_timedelta(df['time_col'], errors='coerce')

步骤2:直接求和

对转换后的列直接调用sum()方法即可得到总时长:

total_duration = df['time_col'].sum()

得到的total_duration是timedelta类型,可直接用于后续的时间计算,比如和其他时间差做加减、求平均值等。

步骤3:可选,转回时分秒字符串格式

如果需要把结果转回和原数据一致的HH:MM:SS字符串格式,可以用以下自定义函数处理:

def format_timedelta_to_hms(td):
    total_sec = int(td.total_seconds())
    hours = total_sec // 3600
    minutes = (total_sec % 3600) // 60
    seconds = total_sec % 60
    return f"{hours:02d}:{minutes:02d}:{seconds:02d}"

# 转换结果示例
print(format_timedelta_to_hms(total_duration))

测试验证

用你给出的示例数据测试:

test_data = ["01:59:55", "00:30:17", "00:09:00", "00:15:03"]
test_df = pd.DataFrame(test_data, columns=["time_col"])
test_df["time_col"] = pd.to_timedelta(test_df["time_col"])
total = test_df["time_col"].sum()
print(format_timedelta_to_hms(total))
# 输出结果为:02:54:15,和手动计算结果一致

大体量数据优化建议

  • 转换前先过滤全空的行,减少无效计算
  • 不需要保留原字符串列的情况下直接覆盖转换,降低内存占用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 03:39:04