print time every n seconds using datetime and % operator

Question:

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())
Asked By: bbartling

||

Answers:

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)
Answered By: W.A

In response to comments on the question: you can do this without datetime and %. The benefit is that it’s much simpler.

import time

POLLING_PERIOD = 0.1 #  seconds


if __name__ == '__main__':
    prev_time = time.time()
    print(time.ctime())
    while True:
        cur_time = time.time()
        if cur_time - prev_time >= 10:
            prev_time = cur_time
            print(time.ctime())
        time.sleep(POLLING_PERIOD)

This script gets the seconds from Unix epoch and prints the current time every 10s. You can adjust the polling period to minimize spinning and ensure that the time is printed only every 10s, rather than 11s, 12s, etc. due to poor resolution.

Please note that this script is susceptible to drift due to inaccuracy of time.sleep() and will eventually print a time which is greater than 10s since the last printed time.


After running some experiments on a system with low load, time.sleep() performs very well over several hours if the sleep time is adjusted based on the difference between the previous and current times.

import time

REPORTING_INTERVAL = 10  # seconds


if __name__ == '__main__':
    prev_time = time.time()
    sleep_time_adj = 0
    print(time.ctime())
    while True:
        time.sleep(REPORTING_INTERVAL - sleep_time_adj)
        print(time.ctime())
        cur_time = time.time()
        sleep_time_adj = cur_time - prev_time - REPORTING_INTERVAL
        prev_time = cur_time

It really comes down to how accurate this needs to be, how long it’s going to run, and the system it will run on.

Answered By: Michael Ruth
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.