如何在python中添加和减去时间
我想写一个简单的时间表脚本。我的输入文件看起来像如何在python中添加和减去时间,python,Python,我想写一个简单的时间表脚本。我的输入文件看起来像 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
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类型求和
感谢评论中的链接,用reduce(operator.add,hours)替换sum(hours)是可行的
剩下的部分是如何测试开始时间是否在12:00之前,结束时间是否在13:00之后,如果是,则将时间增量减少半小时。您在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.
看一看:这里:@Fusseldieb我看了你的链接,谢谢。似乎减少(operator.add,hours)是您添加小时数的方式。如何执行if语句和间隙减法。
a = timedelta(...)
b = timedelta(...)
c = b - a - gap