我正在编写一个使用while循环检查是否在特定时间的程序,如果是特定时间,它会打印一条语句。我已经设置了所有if-statements,但是一旦程序启动,时间就不会更新(如果我在下午6点启动程序,它将始终在当地时间下午6点输出)。有没有办法在while循环中更新时间?

我试图研究日期时间之外的其他functions/methods,但是据我所知,我找不到能够在程序运行时更新时间的任何functions/methods。此外,我在stackoverflow上发现的有关日期时间和语言环境时间的论坛通常只是讲解如何一次获取语言环境时间的论坛(例如Python datetime模块HR:MIN:SEC中的当前时间)。我发现有关语言环境时间的其他论坛也倾向于使用不同的语言,尤其是C#和PHP。如果还有另一个论坛可以回答我的问题,请纠正我!

from datetime import date
from datetime import time
from datetime import datetime
import time
import webbrowser

now = datetime.now()
sleep = False
today = date.today()
roundCheck = 0
print("Awaiting time check...")

while sleep != True:
    print('Up here...')
    if roundCheck != 0:
        print('Stuck in time...')
        time.sleep(60)
    print('Time is done')
    if str(now.strftime('%H')) == '20' and str(now.strftime('%M')) == '05':
        print('Now the while loop will end')
        sleep = True
    roundCheck = 1
    print('Another round has passed')

print('Outside while loop')

时间为20:05时,应将sleep设置为true,并且可以执行while循环之外的print语句。但是,当我在较早的时间(例如20:00)启动程序时,它仅使用该时间检查now.strftime()。

分析解答

now永远不会改变。您只需要将now = datetime.now()放入while循环中即可。