簡體   English   中英

python錯誤if語句上的語法無效

[英]python error invalid syntax on if statement

我的代碼需要幫助。 我想檢查變量start_time是否小於,等於或大於current_time以比較時間。

這是代碼:

start_date = str(stop_date[0])
stop_date = str(stop_date[1])
get_current_time = datetime.datetime.now().strftime('%H:%M')
get_start_time = time.strptime(start_date, '%Y%m%d%H%M%S')
start_time = time.strftime('%H:%M', get_start_time)
get_stop_time = time.strptime(stop_date, '%Y%m%d%H%M%S')
stop_time = time.strftime('%H:%M', get_stop_time)
current_time = str(get_current_time)

if start_time <> current_time <> stop_time:
   print "program is half way"

這是start_time的輸出:

19:00
19:00
19:00
19:00
19:00
19:00
19:00

這是current_time的輸出:

00:10:36 T:5304  NOTICE: 00:09

這是stop_time的輸出:

00:09:33 T:6824  NOTICE: 19:30
00:09:33 T:6824  NOTICE: 20:00
00:09:33 T:6824  NOTICE: 19:30
00:09:33 T:6824  NOTICE: 20:00
00:09:33 T:6824  NOTICE: 20:00
00:09:33 T:6824  NOTICE: 19:30
00:09:33 T:6824  NOTICE: 20:00

當我嘗試這個:

if start_time <=> current_time < stop_time:
   print "program has finished"

這會給我一個錯誤: invalid syntax

它不會讓我在語句中使用= ,我只能在小於或大於或大於的情況下寫在語句上,而不能在=

如何包含等於和大於等於start_time的equal =以將時間與current_time比較?

編輯:對不起,對不起我的錯誤。 我粘貼了錯誤的代碼,所以這是我想要做的:

if start_time <=> current_time < stop_time:
    print "program is half way"

據我了解,您想檢查一下兩者是否成立:

  1. current_time小於,大於或等於start_time
  2. current_time小於stop_time

現在,第一個可以這樣寫:

if current_time < start_time or current_time > start_time or current_time == start_time:
   print "program has finished"

但是,這總是正確的,因為start_timecurrent_time將相等(使current_time == start_time真)或不同(使current_time < start_time or current_time > start_time真)。

第二個可以這樣寫:

if current_time < stop_time:
   print "program has finished"

因此,由於不需要第一個,因此您只需要:

if current_time < stop_time:
   print "program has finished"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM