Search code examples
pythonpandassumtimedelta

sum() not working on lists of Timedelta objects


I have a list of pandas.Timedelta objects

In [31]: r
Out[31]: [Timedelta('0 days 00:00:12'), Timedelta('0 days 00:10:02')]

I can sum them up with the plus operator

In [32]: r[0] + r[1]
Out[32]: Timedelta('0 days 00:10:14')

But not using sum()

In [33]: sum(r)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-33-1ab9ba54065b> in <module>
----> 1 sum(r)

TypeError: unsupported operand type(s) for +: 'int' and 'Timedelta'

Is that expected? I would expect sum() to work in this case. Is there a way to sum the pandas.Timedelta objects in the list without explicitly iterating over it?


Solution

  • From the docs for the sum function

    This function is intended specifically for use with numeric values and may
    reject non-numeric types.
    

    However, you can make it work by passing in a start value (which is integer 0 by default)

    from datetime import timedelta
    r = [timedelta(0), timedelta(days=1)]
    sum(r, timedelta(0))