views:

68

answers:

4

Python: How to get the sum of timedelta?

Eg. I just got a lot of timedelta object, and now I want the sum. That's it!

+3  A: 

To add timedeltas you can use the builtin operator +:

result = timedelta1 + timedelta2

To add a lot of timedeltas you can use sum:

result = sum(timedeltas, datetime.timedelta())

Or reduce:

import operator
result = reduce(operator.add, timedeltas)
Mark Byers
+3  A: 

datetime combine method allows you to combine time with a delta

datetime.combine(date.today(), time()) + timedelta(hours=2)

timedelta can be combined using usual '+' operator

>>> timedelta(hours=3) 
datetime.timedelta(0, 10800)
>>> timedelta(hours=2)
datetime.timedelta(0, 7200)
>>>
>>> timedelta(hours=3) + timedelta(hours=2)
datetime.timedelta(0, 18000)
>>> 

You can read the datetime module docs and a very good simple introduction at

pyfunc
A: 

As this "just works", I assume this question lacks some detail...

Just like this:

>>> import datetime
>>> datetime.timedelta(seconds=10) + datetime.timedelta(hours=5)
datetime.timedelta(0, 18010)
af
A: 

I am pretty sure that by "sum" he means that he wants the value of the sum in a primitive type (eg integer) rather than a datetime object.

Note that you can always use the dir function to reflect on an object, returning a list of its methods and attributes.

>>> import datetime
>>> time_sum=datetime.timedelta(seconds=10) + datetime.timedelta(hours=5)
>>> time_sum
datetime.timedelta(0, 18010)
>>> dir(time_sum)
['__abs__', '__add__', '__class__', '__delattr__', '__div__', '__doc__', '__eq__', '__floordiv__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__mul__', '__ne__', '__neg__', '__new__', '__nonzero__', '__pos__', '__radd__', '__rdiv__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmul__', '__rsub__', '__setattr__', '__str__', '__sub__', 'days', 'max', 'microseconds', 'min', 'resolution', 'seconds']

So in this case, it looks like we probably want seconds.

>>> time_sum.seconds
18010

Which looks right to me:

>>> 5*60*60 + 10
18010
Goladus