1

I have a dictionary having its values as timestamp. Few keys have list of timestamps as values. I am trying to sum timestamps which is in value. But failing with below error:

Traceback (most recent call last):
  File "testing.py", line 53, in <module>
    for key, value in total_exam_items.iteritems():
AttributeError: 'dict' object has no attribute 'iteritems'

Below is my code:

total_items = {'item1': ['0:02:00'], 'item2': ['0:02:13'], 'item3': ['0:04:53'], 'item4': ['0:00:31', '0:05:17'], 'item5': ['0:04:31'], 'item6': ['0:04:34'], 'item6': ['0:13:26', '0:04:24']}
output = defaultdict(datetime)
for key, value in total_items.iteritems():
    output[key] += value

Not sure where I am doing wrong? Any suggestions please???

2 Answers2

2

I think the point here (besides .items()) is that you need to use timedelta if you want the sum of the times at each item, e.g.

from collections import defaultdict
from datetime import timedelta
from pandas import to_timedelta

total_items = {'item1': ['0:02:00'], 'item2': ['0:02:13'], 'item3': ['0:04:53'], 'item4': ['0:00:31', '0:05:17'], 'item5': ['0:04:31'], 'item6': ['0:04:34'], 'item6': ['0:13:26', '0:04:24']}
output = defaultdict(timedelta)

for key, value in total_items.items():
    l = [to_timedelta(s) for s in value]
    for t in l:
        output[key] += t
        
# output
# defaultdict(datetime.timedelta,
#             {'item1': Timedelta('0 days 00:02:00'),
#              'item2': Timedelta('0 days 00:02:13'),
#              'item3': Timedelta('0 days 00:04:53'),
#              'item4': Timedelta('0 days 00:05:48'),
#              'item5': Timedelta('0 days 00:04:31'),
#              'item6': Timedelta('0 days 00:17:50')}) 

Note that I'm using to_timedelta from the pandas lib because it offers convenient parsing of timedeltas from string.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • This logic is superb. But how do we remove upto `Timedelta('0 days ` in the output? – Samudrala Prasad Jun 22 '20 at 06:27
  • @SamudralaPrasad: unfortunately, there is no `strftime` for `timedelta, so you'll need a work-around; see [e.g. here](https://stackoverflow.com/questions/538666/format-timedelta-to-string) to get the idea. – FObersteiner Jun 22 '20 at 06:34
1

If you are using Python3.x

instead of:

for key, value in total_items.iteritems():

Try:

for key, value in total_items.items():
Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61