【发布时间】:2016-10-18 11:20:15
【问题描述】:
我想编写一个简单的时间表脚本。我的输入文件看起来像
9:00 17:00
10:45 12:35
11:00 15:00
我想阅读它,计算每天工作的小时数,然后将这些小时数相加。当一天从 12:00 之前开始到 13:00 之后结束时,我也想减去半小时的午休时间。
到目前为止我的尝试是:
import sys
from datetime import datetime
gap = datetime.strptime('00:30','%H:%M')
hours = []
for line in sys.stdin:
(start_time,end_time) = line.split()
start_time = datetime.strptime(start_time, '%H:%M')
end_time = datetime.strptime(end_time, '%H:%M')
#if start_time before 12:00 and end_time after 13:00 then subtract gap
hours.append(end_time-start_time)
print sum(hours)
我不知道如何使 if 语句行起作用,并且对时间求和似乎也不起作用,因为您无法对 datetime.timedelta 类型求和。
感谢 cmets 中的链接,将 sum(hours) 替换为 reduce(operator.add, hours) 有效。
剩下的部分是如何测试 start_time 是否在 12:00 之前,end_time 是否在 13:00 之后,如果是,则将 timedelta 减少半小时。
【问题讨论】:
-
@Fusselldieb 我查看了您的链接,谢谢。似乎 reduce(operator.add, hours) 是您添加小时数的方式。 if语句和gap减法怎么做。
标签: python