我正在努力解决以下问题:
我如何总结一个timedeltas列表,如:
[datetime.timedelta(0, 3600), datetime.timedelta(0, 3600), datetime.timedelta(0, 7200)]
应该导致 datetime.timedelta(0,14400) => 4小时
答案 0 :(得分:7)
试试这个,
import datetime
print sum(time_list,datetime.timedelta())
结果:
datetime.timedelta(0, 14400)
答案 1 :(得分:3)
将datetime.timedelta(0,0)
作为初始值传递给sum
。
import datetime
arr = [datetime.timedelta(0, 3600), datetime.timedelta(0, 3600), datetime.timedelta(0, 7200)]
print(sum(arr, datetime.timedelta(0,0)))
输出:
4:00:00
答案 2 :(得分:1)
您可以使用pandas
import pandas as pd
df=pd.DataFrame([datetime.timedelta(0, 3600), datetime.timedelta(0, 3600), datetime.timedelta(0, 7200)])
df[0].sum()
Timedelta('0 days 04:00:00')
答案 3 :(得分:1)
另一种解决方案:使用functools.reduce
,
import operator
import functools
import datetime
dts = [datetime.timedelta(0, 3600), datetime.timedelta(0, 3600), datetime.timedelta(0, 7200)]
result = functools.reduce(operator.add, dts)
print(result)
# 4:00:00