【问题标题】:How can I print every minute using Datetime with Python如何在 Python 中使用 Datetime 打印每一分钟
【发布时间】:2017-07-24 19:04:06
【问题描述】:
例如,我想使用时间或日期时间打印“1 分钟”,每经过 1 分钟。我不能使用 time.sleep(60) 因为我有更多的代码需要在每次更新时在 whileloop 中运行。我需要一种方法来检查 datetime.now() 是否大于 1 分钟前。谢谢!
import time
import datetime as dt
t = dt.datetime.now()
while True:
if 60 seconds has passed:
print("1 Min")
【问题讨论】:
标签:
python
loops
datetime
time
【解决方案1】:
这可能是您正在寻找的:
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】:
您可以使用datetime.timedelta 对象来测试是否已超过 60 秒。
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()