sum up all the time delta values in a dictionary

Viewed 216

I have a dictionary with time delta values.

{1: Timedelta('0 days 01:44:39'),
 2: Timedelta('0 days 02:34:01'),
 3: Timedelta('0 days 00:49:15'),
 4: Timedelta('0 days 01:13:26'),
 5: Timedelta('0 days 00:38:14')}

I want to sum up all the values and show a total timestamp (addition of all the time stamps) as an output. any idea how to achieve this requirement?

I tried converting it into list and then used sum() function but they didn't work with timestamps.

3 Answers

sum(iterable, start)
iterable : iterable can be anything list , tuples or dictionaries , but most importantly it should be numbers.

start : this start is added to the sum of numbers in the iterable.

From above you can say sum function works on numbers only.

To make it work with timedeltas use Python's datetime module. Do below:

In [804]: d = {1: Timedelta('0 days 01:44:39'),
     ...:  2: Timedelta('0 days 02:34:01'),
     ...:  3: Timedelta('0 days 00:49:15'),
     ...:  4: Timedelta('0 days 01:13:26'),
     ...:  5: Timedelta('0 days 00:38:14')}

In [805]: import datetime

In [803]: sum(d.values(), datetime.timedelta())
Out[803]: Timedelta('0 days 06:59:35')

Time performance of all answers for small dataset:

@jezrael's answer:

In [806]: def j():
     ...:     s = pd.Series(d)
     ...:     return s.sum()
     ...: 

In [807]: %timeit j()
491 µs ± 86.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

@Pablo's answer:

In [810]: %timeit reduce(lambda a,b: a+b, d.values())
22.7 µs ± 250 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

@my answer:

In [808]: %timeit sum(d.values(), datetime.timedelta())
31.9 µs ± 451 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Convert dictionary to Series, so possible use sum of timedeltas which exclude None, NaN by default:

d = {1: pd.Timedelta('0 days 01:44:39'),
 2: pd.Timedelta('0 days 02:34:01'),
 3: pd.Timedelta('0 days 00:49:15'),
 4: pd.Timedelta('0 days 01:13:26'),
 5: pd.Timedelta('0 days 00:38:14')}

s = pd.Series(d)
print (s.sum())
0 days 06:59:35

You can use functools.reduce:

>>> from functools import reduce
>>> d = {1: pd.Timedelta('0 days 01:44:39'),
 2: pd.Timedelta('0 days 02:34:01'),
 3: pd.Timedelta('0 days 00:49:15'),
 4: pd.Timedelta('0 days 01:13:26'),
 5: pd.Timedelta('0 days 00:38:14')}
>>> reduce(lambda a,b: a+b, d.values())
#Timedelta('0 days 06:59:35')
Related