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.
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.
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)
Use datetime. timedelta. total_seconds() to convert timedelta to seconds. Call timedelta.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With