我是Python的新手,我遇到了一些问题。我有一个包含以下信息的文本文件:
[Name, Start Time, Finish Time]
Xantippe 09:00 11:00
Erica 10:00 12:06
Marcia 09:30 11:45
Elizabeth 10:15 12:10
Angela 11:30 13:45
Freda 12:00 14:20
Maria 12:30 14:10
我需要能够读取文本文件,获取每个人的开始和结束时间,计算时差并将信息写入按升序排列时间的文件中。我有标准方法来计算两次之间的时差,并按如下方式对信息进行排序,但是我无法从文本文件中识别时间并执行任务。有人可以帮忙吗?
import datetime as dt
class TimeCalc:
start = "09:35:23"
end = "10:23:00"
start_dt = dt.datetime.strptime(start, '%H:%M:%S')
end_dt = dt.datetime.strptime(end, '%H:%M:%S')
diff = (end_dt - start_dt)
diff.seconds / 60
print(diff)
with open('Lad.txt') as fin:
lines = [line.split() for line in fin]
from operator import itemgetter
lines.sort(key=itemgetter(2), reverse=True)
with open('sortdesc.txt', 'w') as fout:
for el in lines:
fout.write('{0}\n'.format(' '.join(el)))
答案 0 :(得分:0)
我不完全清楚你的格式。对于逗号分隔和时间12:00:00
,这应该有效:
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))