How to get the sum of timedelta in Python?
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)
If you have a list of timedelta objects, you could try:
datetime.timedelta(seconds=sum(td.total_seconds() for td in list_of_deltas))
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
- http://www.doughellmann.com/PyMOTW/datetime/