2011-12-05 59 views
-1

可能重複:
I'm new to python, I can't tell if this will work or not我不知道這段代碼有什麼問題嗎?

import time 
from sys import stdout 
varthing = 1 
while varthing == 1: 
    time.sleep(1) 
    checker = time.strftime("\r%b, %d %H:%M:%S", time.localtime()) 
    print checker, 
    stdout.flush() 
    if checker == "Dec, 25 00:00:00" : 
     print "It's Christmas" 
     raw_input("Enter anything to close\n") 
     varthing = 0 

我看不出有什麼不妥。這是聖誕節時通知你的時鐘。

+1

你有什麼期望發生,而是發生了什麼? –

+0

什麼也沒有發生,它只是計數,當它達到指定的日期時,什麼都不會發生。 – user1080694

回答

5
  • 您的strftime格式以\r開頭。爲什麼?您在if語句中測試的字符串永遠不會匹配,因爲它不以\r開頭。

  • time.sleep(1)不能保證睡一秒鐘。它可能會延長睡眠時間,您會錯過checker與您測試的字符串匹配的一秒鐘窗口。

+0

有沒有更好的方法來做到這一點? – user1080694

+2

+1 - 在一秒鐘窗口的事情上,我的建議是測試一個單獨格式的日期字符串,不包括時間。 – Steve314

+0

'睡(0.5)'也可以工作。 – 9000

0

如果不需要打印每一秒,這將這樣的伎倆:

import datetime, time 
target_date = datetime.datetime(2011, 12, 25) 
time_left = target_date - datetime.datetime.now() 
time.sleep(time_left.total_seconds()) 
print "It's Christmas"