jordyn jordyn - 3 months ago 16
Python Question

How to calculate timedelta pairs from a dictionary

I have a dictionary with key-value pairs of type timedelta in '%H:%M:%S'

i.e.

myDict = {'0:00:12': '0:40:10', '0:00:18': '0:04:58', '0:00:50': '0:02:35'}


What I want to be able to do is calculate the difference between the key and the value for each pair and save those those differences to a list

i.e. for first pair
'0:40:10' - '0:00:12'


Calculate
'0:40:10' - '0:00:12'


Which is
0:39:58
, then save that to myList, so that myList looks like:

myList = ['0:39:58', 'difference-for-pair-2', 'difference-for-pair-3' ... ]


I got as far as

FMT='%H:%M:%S'
for key, value in myDict.iteritems():
print datetime.strptime(value, FMT) - datetime.strptime(key, FMT)


this prints the differences in times I want like:

0:02:05
0:02:57
0:00:31
...


Which is correct, but I can't figure out how to save these values to a list rather than just printing on screen

How do I do this?

Answer

Combining the answers of @wim @user35269 and @RandyTek Here is the final code. Note that converting the datetime object to string will give you the desired output, to save or print out later:

from datetime import datetime

myDict = {'0:00:12': '0:40:10', '0:00:18': '0:04:58', '0:00:50': '0:02:35'}
FMT = '%H:%M:%S'
results = []
for key, value in myDict.iteritems():
    result = datetime.strptime(value, FMT) - datetime.strptime(key, FMT)
    results.append(str(result))

print results

Here is how it look:

['0:04:40', '0:39:58', '0:01:45']