2016-10-18 52 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