How to get the sum of timedelta in Python?

user469652 picture user469652 · Oct 29, 2010 · Viewed 26.6k times · Source

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!

Answer

Mark Byers picture Mark Byers · Oct 29, 2010

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)