pauljohn32
pauljohn32

Reputation: 2255

Trouble summing timedelta objects; previously recommended solutions don't work in python 3.7

I have a followup on this question about summing time delta objects: TypeError using timedelta, cannot sum times

Answers to that question explain that sum() expects to add integers, and you need to make sure it knows you are adding time delta objects. Solution is to insert a list item "datetime.timedelta(0)" to give sum the hint.

I do not understand this error I'm getting in python 3.7. As in other question, I need a sum of time delta objects. Was trying code that used a list comprehension to extract timedelta values, got same error as other question:

sum([i.time_idle for i in qalt])
*** TypeError: unsupported operand type(s) for +: 'int' and 'Timedelta'

The puzzle for me is that the second object in my list is actually the one that is recommended as the solution in the previous question. Inspect

[i.time_idle for i in qalt]
[Timedelta('0 days 00:18:40.649903'), datetime.timedelta(0)]

I can add the time delta objects manually:

 tlist = [i.time_idle for i in qalt]
 tlist[0] + tlist[1]
 Timedelta('0 days 00:18:40.649903')

However, the sum function still does not work

 sum(tlist)
*** TypeError: unsupported operand type(s) for +: 'int' and 'Timedelta'

In case you want to play with this, I believe following provides an MRE test case:

 klist = [datetime.timedelta(days=0, hours=0, minutes=18, seconds=40), datetime.timedelta(0)]

You'll see that sum(klist) fails, but can run klist[0] + klist[1]

I'm using a workaround that harkens back to my C roots:

time_idle_total = datetime.timedelta(seconds=0)
for i in qalt:
    time_idle_total += i.time_idle

Upvotes: 1

Views: 104

Answers (1)

LeopardShark
LeopardShark

Reputation: 4416

You can think of it in terms of your workaround loop:

time_idle_total = datetime.timedelta(seconds=0)
for i in qalt:
    time_idle_total += i.time_idle

What sum does is effectively this:

time_idle_total = 0
for i in qalt:
    time_idle_total += i.time_idle

The second argument of sum gives the initial value to begin the sum, but you only pass one argument to sum (a list which happens to have a timedelta zero as its second element). So you still need to use sum([i.time_idle for i in qalt], datetime.timedelta(0))

Note that sum((i.time_idle for i in qalt), datetime.timedelta(0)) should be slightly faster (generator comprehension instead of list).

Upvotes: 2

Related Questions