问题
As an example, I want to print, "1 min", every time 1 minute has passed using time or datetime. I cant use time.sleep(60) because I have more code that needs to run in the whileloop every update. I need a way to check if datetime.now() is greater than 1 minute ago. Thanks!
import time
import datetime as dt
t = dt.datetime.now()
while True:
if 60 seconds has passed:
print("1 Min")
回答1:
This may be what you are looking for:
import datetime as dt
from time import sleep
t = dt.datetime.now()
minute_count = 0
while True:
delta_minutes = (dt.datetime.now() -t).seconds / 60
if delta_minutes and delta_minutes != minute_count:
print("1 Min has passed since the last print")
minute_count = delta_minutes
sleep(1) # Stop maxing out CPU
回答2:
You can use a datetime.timedelta object to test if over 60 seconds have elapsed.
import datetime as dt
# Save the current time to a variable ('t')
t = dt.datetime.now()
while True:
delta = dt.datetime.now()-t
if delta.seconds >= 60:
print("1 Min")
# Update 't' variable to new time
t = dt.datetime.now()
来源:https://stackoverflow.com/questions/42599733/how-can-i-print-every-minute-using-datetime-with-python