need the average from a list of timedelta objects

☆樱花仙子☆ 提交于 2019-12-06 17:40:51

问题


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 pythons 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.


回答1:


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.




回答2:


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.




回答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)



回答4:


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.



来源:https://stackoverflow.com/questions/5006258/need-the-average-from-a-list-of-timedelta-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!