Sum list of datetime.time

Viewed 307

I have a list of datetime.time

[ datetime.time(2, 0), datetime.time(1, 0), datetime.time(1, 0), ...]

How can I do the sum of those values ? I tried to simply to

sum(mylist)

but I have an error "unsupported operand type(s) for +: 'int' and 'datetime.time'"

2 Answers

You need to specify the start=… parameter, such that it does not start with 0, but with a timedelta` with a duration that is zero.

Furthermore you can not add up two time items, since it makes no sense to add two o'clock and five o'clock. You should work with a timedelta:

from datetime import timedelta

data = [timedelta(hours=2), timedelta(hours=1), timedelta(hours=1)]

and then sum these up with:

sumd = sum(data, start=timedelta())

Like this

import datetime as dt
t1 = dt.datetime.strptime('12:00:00', '%H:%M:%S')
t2 = dt.datetime.strptime('02:00:00', '%H:%M:%S')
time_zero = dt.datetime.strptime('00:00:00', '%H:%M:%S')
print((t1 - time_zero + t2).time())
Related