jordyn jordyn - 1 year ago 99
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'


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'

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

Which is
, 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

for key, value in myDict.iteritems():
print datetime.strptime(value, FMT) - datetime.strptime(key, FMT)

this prints the differences in times I want like:


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 Source

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)

print results

Here is how it look:

['0:04:40', '0:39:58', '0:01:45']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download