Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

print time every n seconds using datetime and % operator

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading