Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum a list with timedeltas in Python [duplicate]

I'm struggling with following problem:

How can I sum a list of timedeltas like:

[datetime.timedelta(0, 3600), datetime.timedelta(0, 3600), datetime.timedelta(0, 7200)]

which should result in datetime.timedelta(0, 14400) => 4 hours

like image 915
Into Numbers Avatar asked Feb 27 '17 13:02

Into Numbers


3 Answers

Try this,

import datetime
print sum(time_list,datetime.timedelta())

Result:

datetime.timedelta(0, 14400)
like image 148
Rahul K P Avatar answered Nov 08 '22 14:11

Rahul K P


Pass datetime.timedelta(0,0) to sum as init value.

import datetime

arr = [datetime.timedelta(0, 3600), datetime.timedelta(0, 3600), datetime.timedelta(0, 7200)]

print(sum(arr, datetime.timedelta(0,0)))

Output:

4:00:00
like image 8
gzc Avatar answered Nov 08 '22 15:11

gzc


You can use 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')
like image 1
NinjaGaiden Avatar answered Nov 08 '22 13:11

NinjaGaiden