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!
timedelta(days=3, hours=5, seconds=10). seconds -> 18010 . It should be 277210s ((3*24*60*60) + (5*60*60) + 10). Better solution: time_sum.
A timedelta has only one method called timedelta. total_seconds() . This method returns the total number of seconds the duration has. If we want to convert a timedelta object to seconds, we can just call it.
To round the Timedelta with specified resolution, use the timestamp. round() method.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With