简体   繁体   English

为什么打印功能不起作用? 为什么 print function 没有在特定时间输出?

[英]Why is the print func not working? Why is the print function not outputing at the specific time?

I am trying to print the current time at a specific time, how come it is not printing what I want it to do?我试图在特定时间打印当前时间,为什么它没有打印我想要它做的事情? it is just exiting at code 0 when it get to the specific time(12:09)当它到达特定时间(12:09)时,它只是在代码 0 处退出

from datetime import datetime as dt

now = dt.now()

current_time = now.strftime("%H:%M")

for i in range(500000000):
    if current_time == "12:09":
        print("The time is" + current_time)

You're only getting the time once.你只有一次机会。 After you do current_time = now.strftime("%H:%M") , the current_time variable isn't going to change.在执行current_time = now.strftime("%H:%M")之后, current_time变量不会改变。 If you want that, you need to move that code inside the loop so that they get run repeatedly:如果需要,您需要将该代码移动到循环内,以便它们重复运行:

for i in range(500000000):
    now = dt.now()                                # move these lines
    current_time = now.strftime("%H:%M")          # inside the loop

    if current_time == "12:09":
        print("The time is" + current_time)

Note that this code is going to thrash your CPU pretty hard, since the loop doesn't take any significant amount of time, and will likely see the same time string thousands or more times in a row.请注意,此代码将非常严重地破坏您的 CPU,因为循环不会占用任何大量时间,并且可能会连续数千次或更多次看到相同的时间字符串。 You may want to call time.sleep or a similar function to delay 30+ seconds between checks of the time (since you only care about the minutes).您可能需要调用time.sleep或类似的 function 以在检查时间之间延迟 30 秒以上(因为您只关心分钟)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM