16

I have created a list of timedelta objects and i need to get the average of this list. when i try to do

return (sum(delta_list)/(len(delta_list)-1))

i get

TypeError: unsupported operand type(s) for +: 'int' and 'datetime.timedelta'

I am new at working with python's datetime classes. I also would like to know how to get this average into a format like days: hours: mins: i don't need anything smaller than mins.

Nicolas
  • 19
  • 4
Cory
  • 513
  • 5
  • 14

4 Answers4

31

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.

Jochen Ritzel
  • 104,512
  • 31
  • 200
  • 194
4

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.

Michal Chruszcz
  • 2,452
  • 16
  • 20
  • I realized it was wrong. I got confused from other sample code from http://stackoverflow.com/questions/179716/average-difference-between-dates-in-python – Cory Feb 15 '11 at 16:38
3

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)
David Webb
  • 190,537
  • 57
  • 313
  • 299
1

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.

jathanism
  • 33,067
  • 9
  • 68
  • 86