need the average from a list of timedelta objects

A datetime.timedelta object has attributes to access the days, microseconds, and seconds. You can reference these easily, for example:

>>> import datetime
>>> daybefore = datetime.timedelta(days=1)
>>> dayminus2 = datetime.timedelta(days=2, minutes=60)
>>> daybefore.days
1
>>> dayminus2.days, dayminus2.seconds
(2, 3600)

To get minutes you're going to have to divide seconds by 60.


sum wants a starting value, which is 0 by default, but 0 can't be added to a timedelta so you get the error.

You just have to give sum a timedelta() as the start value:

# this is the average
return sum(delta_list, timedelta()) / len(delta_list)

To print it out you can do this:

print str(some_delta)

If you want something customized you can get some_delta.days and some_delta.seconds but you have to calculate everything between.


First of all, sum adds all of the elements from the list to an initial value, which is by default 0 (an integer with value of zero). So to be able to use sum on a list of timedelta's, you need to pass a timedelta(0) argument - sum(delta_list, timedelta(0)).

Secondly, why do you want to subtract one from the length of the list? If a list is of length 1 you'll get a ZeroDivisionError.

Having fixed the above you'll end up with a timedelta object being an average. How to convert that to a human-readable format I'm leaving for you as an exercise. The datetime module documentation should answer all of the possible questions.


The sum() function needs a start value to add all the items in the iterable to. It defaults to 0 which is why you're getting the error about adding a timedelta to an int.

To fix this, just pass a timedelta object as the second argument to sum:

(Creating a timedelta with no arguments creates one corresponding to a zero time difference.)

Also, the mean of a set of items is usually the sum of items divided by the number of items so you don't need to subtract 1 from len(delta_list).

These changes mean we can remove some of the brackets from your statement.

So this gives you:

return sum(delta_list,timedelta()) / len(delta_list)