How can I print every minute using Datetime with Python

荒凉一梦 提交于 2021-01-28 05:02:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!