2015-02-11 140 views
0

我在這裏有一些問題。我想在所需的時間停止print命令。我想出了一些代碼,它仍然保持循環。這裏的代碼,Python:在所需時間停止

import time 
t = time.strftime("%H%M%S") 
while ti: 
    print(time.strftime("%H%M%S")) 
    time.sleep(1) 
    if t = ("140000"): #just example of time to stop print 
     break 

感謝

回答

0

這將工作

import time 
t = time.strftime("%H%M%S") 
while t: 
    t = time.strftime("%H%M%S") 
    print(time.strftime("%H%M%S")) 
    time.sleep(1) 
    if t == ("140000"): #just example of time to stop print 
     break 

您在代碼中有一些錯誤

  1. 而TI: - >而T:

  2. 當t =( 「140000」): - >當t = =( 「140000」):

  3. 和你丟失此線T = time.strftime( 「%H%M%S」)
+1

應該''='(並使用時間戳,而不是字符串),因爲你不知道循環需要多長時間 – 2015-02-11 10:34:46

-1

試試這個:

import time 

while ti: 
    t = time.strftime("%H%M%S") 
    print(time.strftime("%H%M%S")) 
    time.sleep(1) 
    if t = ("140000"): #just example of time to stop print 
     break 
1
t = time.strftime("%H%M%S") 

循環之前只執行一次,所以t的值不會永遠改變。

您的方法是檢查時差的最差方法; python的datetime框架允許時間戳的減法,因此,你可以檢查,因爲別的事情極易發生沒有做任何字符串比較的時間...

0

time.sleep(1)可以睡眠少於或多於一個第二因此t == "140000"是不夠的。

要在給定的本地時間停止循環:「自新紀元的秒數​​」

import time 
from datetime import datetime 

stop_dt = datetime.combine(datetime.now(), datetime.strptime("1400", "%H%M").time()) 
stop_time = time.mktime(stop_dt.timetuple()) 
while time.time() < stop_time: 
    print(time.strftime("%H%M%S")) 
    time.sleep(max(1, (stop_time - time.time()) // 2)) 

time.time()回報 - 與字符串比較它的作品跨越午夜。

睡眠間隔是剩餘時間的一半或一秒(無論大)。

time.mktime()如果當本地時間不明確時基於字符串的解決方案可能停止兩次,如果停止時間在DST結束轉換期間返回錯誤結果(「回退」)。