2016-07-26 47 views
0
這裏

當另一個時間是第二天時,您如何在兩次之間設置簡單定時器?

from datetime import datetime, time 
now = datetime.now() 
now_time = now.time() 

if now_time >= time(10,30) and now_time <= time(13,30): 
    print "yes, within the interval" 

Python的小白,我想計時器到今天上午10,30和第二天上午10點之間運行。將時間(13,30)更改爲時間(10,00)將不起作用,因爲我需要告訴python 10,00是第二天。我應該使用日期時間函數,但不知道如何。任何提示或例子表示讚賞。

+0

你有沒有考慮過使用UNIX時間戳,這算的秒數?只需設置一個等待任務之間適當秒數的時間即可 – Matt

回答

1

datetime課程中的combine方法將對您有所幫助,timedelta類也會有所幫助。以下是你將如何使用它們:

from datetime import datetime, timedelta, date, time 

today = date.today() 
tomorrow = today + timedelta(days=1) 

interval_start = datetime.combine(today, time(10,30)) 
interval_end = datetime.combine(tomorrow, time(10,00)) 

time_to_check = datetime.now() # Or any other datetime 

if interval_start <= time_to_check <= interval_end: 
    print "Within the interval" 

請注意我是如何進行比較的。 Python可以讓你「嵌套」這種比較,通常比編寫if start <= x and x <= end更簡潔。

P.S.有關這些類的更多詳細信息,請閱讀https://docs.python.org/2/library/datetime.html

1

考慮一下:

from datetime import datetime, timedelta 

now = datetime.now() 
today_10 = now.replace(hour=10, minute=30) 
tomorrow_10 = (now + timedelta(days=1)).replace(hour=10, minute=0) 

if today_10 <= now <= tomorrow_10: 
    print "yes, within the interval" 

的邏輯是創建3個datetime對象:一個是今天上午10點,一個是現在和一個明天上午10點。他們只是檢查條件。

0

爲便於比較創建時對象的替代方法是簡單地查詢hourminute屬性:

now= datetime.now().time() 
if now.hour<10 or now.hour>10 or (now.hour==10 and now.minute>30): 
    print('hooray') 
相關問題