Home > other >  print time every n seconds using datetime and % operator
print time every n seconds using datetime and % operator

Time:12-31

How do I print the time every 10 seconds based off of using the % operator and the datetime package? This only prints once...

from datetime import datetime, timezone, timedelta
import time

now_utc = datetime.now(timezone.utc)

while True:
    if (now_utc - datetime.now(timezone.utc)).total_seconds() % 10 == 0:
        print(time.ctime())

CodePudding user response:

To print the time every 10 seconds, you can use the sleep() function from the time module to pause the loop for the desired interval.

import time
from datetime import datetime, timezone

while True:
    now_utc = datetime.now(timezone.utc)
    if (now_utc - datetime.now(timezone.utc)).total_seconds() % 10 == 0:
        print(time.ctime())
    time.sleep(10)
  • Related