Skip to content Skip to sidebar Skip to footer

Python - Calculating Time Difference From Text File

I am very new to Python and i'm having some problems. I have a text file containing the following information: [Name, Start Time, Finish Time] Xantippe 09:00 11:00 Erica 10:00 12:

Solution 1:

i'm not totally clear on your formatting. for comma delimited and time like 12:00:00, this should work:

from datetime import datetime

def time_diff(start, end):
    start_dt = datetime.strptime(start, '%H:%M:%S')
    end_dt = datetime.strptime(end, '%H:%M:%S')
    diff = (end_dt - start_dt)
    return diff.seconds

scores = {}
with open('input.txt') as fin:
    for line in fin.readlines():
        values = line.split(',')
        scores[values[0]] = time_diff(values[1],values[2])

with open('sorted.txt', 'w') as fout:
    for key, value in sorted(scores.iteritems(), key=lambda (k,v): (v,k)):
        fout.write('%s,%s\n' % (key, value))

Post a Comment for "Python - Calculating Time Difference From Text File"