我想写一个简单的时间表脚本。我的输入文件看起来像
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类型求和。
感谢评论中的链接,用减少(operator.add,hours)替换sum(hours)可以正常工作。
剩下的部分是如何测试start_time是否在12:00之前,end_time是在13:00之后,如果是,则将timedelta减少半小时。
答案 0 :(得分:2)
您在if语句中使用了错误的代码(和语法)。
if start_time < datetime.strptime('12:00', '%H:%M') and end_time > datetime.strptime('13:00', '%H:%M'):
delta_hours = end_time.hour - start_time.hour)
delta_minutes = end_time.minutes - start_time.minutes)
# Do whatever your want with it now.
# Substraction of the break is not implemented in this example, it depends on how you want to save it.
Time delta可能也值得研究,它可以使用
等基本操作a = timedelta(...)
b = timedelta(...)
c = b - a - gap