'How can I print every minute using Datetime with Python

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")


Solution 1:[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

Solution 2:[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()

Solution 3:[3]

how to print every second for sepcific datetime

input

import datetime,time

start_time = datetime.datetime.strptime('05/10/09 18:00:00', '%d/%m/%y %H:%M:%S')

while True:
  start_time += datetime.timedelta(microseconds=1,milliseconds=1,seconds=1)
  print(start_time)
  time.sleep(1)

output

2009-10-05 18:00:01.001001
2009-10-05 18:00:02.002002
2009-10-05 18:00:03.003003
2009-10-05 18:00:04.004004
2009-10-05 18:00:05.005005
2009-10-05 18:00:06.006006
2009-10-05 18:00:07.007007
2009-10-05 18:00:08.008008
2009-10-05 18:00:09.009009
2009-10-05 18:00:10.010010
2009-10-05 18:00:11.011011
2009-10-05 18:00:12.012012
2009-10-05 18:00:13.013013
2009-10-05 18:00:14.014014
2009-10-05 18:00:15.015015
2009-10-05 18:00:16.016016
2009-10-05 18:00:17.017017
2009-10-05 18:00:18.018018

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user3079474
Solution 2 tsherwen
Solution 3