2016-10-18 53 views
0

我想编写一个简单的时间表脚本。我的输入文件看起来像如何在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 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语句行的工作和总结的时间似乎并没有工作,要么因为你不能总结日期时间。 timedelta类型。


由于在评论中的链接,以替换和减少(小时)(operator.add,小时)的作品。

剩下的部分是如何测试start_time是否在12:00之前,end_time是在13:00之后,如果是这样可以将timedelta缩短半个小时。

+3

请看:http://stackoverflow.com/questions/13897246/python-time-subtraction – Fusseldieb

+0

和这里:http://stackoverflow.com/questions/3096953/difference-between-two-time-intervals-in-python – Fusseldieb

+0

@Fusseldieb我看着你的链接谢谢你。看起来减少(operator.add,小时)是你如何添加小时。你如何做if语句和差距减法。 – eleanora

回答

1

您在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. 

​​可能是值得探讨中,也可以使用基本操作,如

a = timedelta(...) 
b = timedelta(...) 
c = b - a - gap