我想在python程序中显示时间。当我启动程序时,它得到了时间,但它没有改变。下面是我的代码:
import time
import pytz
from datetime import datetime
current_time = datetime.now(pytz.timezone('Europe/Madrid')).strftime("%H:%M:%S")
while True:
print(current_time)
time.sleep(5)
我总是得到相同的时间,我不知道为什么
您没有更新程序中的时间。
datetime.now
结果只在变量current_time
中存储一次。
如果您想获得每次循环迭代的当前时间:
import time
import pytz
from datetime import datetime
while True:
#update the time here
current_time = datetime.now(pytz.timezone('Europe/Madrid')).strftime("%H:%M:%S")
print(current_time)
time.sleep(5)
您只在循环外分配一次current_time
变量-您每5秒显示current_time
,但您也需要每5秒更新一次时间。
要解决这个问题,将变量赋值移到循环中。
import time
import pytz
from datetime import datetime
while True:
current_time = datetime.now(pytz.timezone('Europe/Madrid')).strftime("%H:%M:%S")
print(current_time)
time.sleep(5)