Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the sum of timedelta in Python?

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!

like image 676
user469652 Avatar asked Oct 29 '10 07:10

user469652


People also ask

How do you sum Timedelta in Python?

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.

What does Timedelta return Python?

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.

How do you round Timedelta?

To round the Timedelta with specified resolution, use the timestamp. round() method.


Video Answer


2 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)
like image 99
Mark Byers Avatar answered Oct 14 '22 08:10

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

  • http://www.doughellmann.com/PyMOTW/datetime/
like image 44
pyfunc Avatar answered Oct 14 '22 08:10

pyfunc