32

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!

David
  • 363
  • 1
  • 4
  • 19
user469652
  • 48,855
  • 59
  • 128
  • 165
  • ???? dont understand the question. Do you have a formula ? – Phong Oct 29 '10 at 07:27
  • 2
    What do you do if you have a lot of integer objects, and you want the sum? What have you tried? What happened when you tried? – John Machin Oct 29 '10 at 09:17
  • 2
    my guess is that if you have tds = [ timedelta(), timedelta(), timedelta(), ...], he wants to know how to do sum(tds). This is not possible as is, as sum kind starts with 0 and hence try to do 0+timedelta(). You can of course do it with some basic loop duration = timedelta(0); for td in tds: duration += td – orzel Jun 07 '17 at 14:55

6 Answers6

59

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)
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • Hmmm, I would expect the sum function to work too, but it appears not for me on 2.7.3. The following fails: ``sum([datetime.timedelta(1), datetime.timedelta(0, 14700)])``. – pelson Nov 29 '12 at 11:44
  • 8
    @pelson: You are missing the second parameter. `sum([datetime.timedelta(1), datetime.timedelta(0, 14700)], datetime.timedelta())` gives `datetime.timedelta(1, 14700)`. – Mark Byers Nov 29 '12 at 12:09
  • Cool. Thanks @Mark_Byers, I did miss that! – pelson Nov 29 '12 at 17:15
  • 14
    To guide others that might be searching for this, the error you get without the second parameter is ``TypeError: unsupported operand type(s) for +: 'type' and 'datetime.timedelta'``. And the official docs that explain why this second argument is needed are [here](http://docs.python.org/2/library/functions.html#sum). – Filipe Correia Feb 01 '13 at 17:15
  • 2
    nice answer using reduce. – levi Oct 20 '15 at 18:39
  • 1
    python3 users will need `from functools import reduce` – JamesL May 01 '22 at 18:45
14

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

pyfunc
  • 65,343
  • 15
  • 148
  • 136
1

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

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

caldweln
  • 126
  • 3
0

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)
af.
  • 1,648
  • 1
  • 11
  • 11
0

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
Doug F
  • 350
  • 2
  • 10
  • 1
    This doesn't work for timedeltas with a `days` component: `datetime.timedelta(days=3, hours=5, seconds=10).seconds -> 18010`. It should be 277210s ((3*24*60*60) + (5*60*60) + 10). – RobM Jan 18 '11 at 16:48
  • Better solution: `time_sum.total_seconds()` (includes seconds from the days component as well) http://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds – balleyne Jan 10 '13 at 06:03
0

(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.

RobM
  • 8,373
  • 3
  • 45
  • 37
  • that's completely irrelevant to the question. – SilentGhost Jan 18 '11 at 16:55
  • Not necessarily. I share Goladus's interpretation - that user469652 wants to sum the components of a timedelta into a single primitive type, such as seconds. That's certainly what I was looking for when I found this question. – RobM Jan 18 '11 at 17:05
  • 2
    Better solution: `myTimeDelta.total_seconds()` http://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds – balleyne Jan 10 '13 at 06:04