How to get the sum of timedelta in Python?

Question:

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!

Asked By: user469652

||

Answers:

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)
Answered By: Mark Byers

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

Answered By: pyfunc

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)
Answered By: af.

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
Answered By: Doug F

(Edit: Assuming that by “sum timedelta” you mean “convert a timedelta to int seconds”.)

This is very inefficient, but it is simple:

int((datetime.datetime.fromtimestamp(0) + myTimeDelta).strftime("%s"))

This converts a Unix timestamp (0) into a datetime object, adds your delta to it, and then converts back to a Unix time. Since Unix time counts seconds, this is the number of seconds your timedelta represented.

Answered By: RobM

If you have a list of timedelta objects, you could try:

datetime.timedelta(seconds=sum(td.total_seconds() for td in list_of_deltas))

Answered By: caldweln
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.