Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

need the average from a list of timedelta objects

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.

like image 563
Cory Avatar asked Feb 15 '11 16:02

Cory


People also ask

What is the use of Timedelta () function?

timedelta() function. Python timedelta() function is present under datetime library which is generally used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations.

What is a Timedelta object?

timedelta Objects. A timedelta object represents a duration, the difference between two dates or times. class datetime. timedelta (days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

How do you convert Timedelta to seconds?

Use datetime. timedelta. total_seconds() to convert timedelta to seconds. Call timedelta.


2 Answers

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.

like image 65
Jochen Ritzel Avatar answered Sep 27 '22 19:09

Jochen Ritzel


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.

like image 34
Michal Chruszcz Avatar answered Sep 27 '22 20:09

Michal Chruszcz