Skip to main content
 首页 » 编程设计

python之datetime.time 数据集的总和

2025年01月19日7shangdawei

我想求和data1,也就是pandas.core.series.Series。

data1: 
 
0        00:06:44 
1        00:00:34 
2        00:02:32 
3        00:00:18 
4        00:03:42 
5        23:59:58 

总计 = 总和(df.data1) 但是,我得到了这样的错误:

--------------------------------------------------------------------------- 
TypeError                                 Traceback (most recent call last) 
<ipython-input-128-9cc06aed3448> in <module>() 
      4  
      5 #print(df.data1) 
----> 6 total = sum(df.data1) 
 
TypeError: unsupported operand type(s) for +: 'int' and 'datetime.time' 

我该如何纠正它?

请您参考如下方法:

datetime.times 的sum 没有在 python 中实现,所以可能的解决方案是转换值 to_timedelta首先:

total = pd.to_timedelta(df.data1.astype(str)).sum() 
print (total) 
1 days 00:13:48 
 
print (int(total.total_seconds())) 
87228 

或者使用 generator 和时间的 sum 组件:

total = sum(x.hour *3600 + x.minute * 60 + x.second for x in df.data1) 
print (total) 
87228