Search code examples
pythonsleep

Python time.sleep() being ignored in timer program


I have been trying to create an extremely simple timer program for the past few days. However, I have come across a major roadblock, in which the second delay countdown is just completely ignored when running the program. I have tried replacing time.sleep(1) with time.sleep(1000), rearranging it all over the while loop it is in, but to no avail. The program just runs, with no delay neither in the beginning nor during the loop.

import time
hour, minute, second = 1, 2, 10

print("Starting now.")
x = 1
while x < 2:
    print(str(hour) + ":" + str(minute) + ":" + str(second)) 
    time.sleep(1)
    second = second - 1
    if second == 0:
        minute = minute - 1
        second = second + 60
        if minute ==0:
            hour = hour - 1
            minute = minute + 60
            if hour == 0:
                x = x + 1

It would be a great help if someone could figure this out. Thank you!


Solution

  • As others have commented the code as given in original question does correctly sleep in a properly configured environment, this answer addresses the logic issue in the time handling by using datetime. The timedelta from subtracting two datetimes does not provide hours and minutes so these are calculated from the seconds.

    import time, datetime,math
    
    d = datetime.timedelta(hours=1,minutes=2,seconds=10)
    endtime = (datetime.datetime.now()+ d)
    
        print("Starting now.")
        while datetime.datetime.now().time() <endtime.time():
            td = endtime - datetime.datetime.now()
            print(str(math.floor(td.seconds / 3600)) + ":" +
                  str(math.floor(td.seconds / 60) - math.floor(td.seconds / 3600)*60 ) + ":" +
                  str(td.seconds - math.floor(td.seconds / 60)*60) ) 
            time.sleep(1)
    

    You can also correct the logic in the original in the following manner

    import time
    hour, minute, second = 1, 2, 10
    
    print("Starting now.")
    x = 1
    while x < 2:
        print(str(hour) + ":" + str(minute) + ":" + str(second)) 
        time.sleep(1)
        second = second - 1
        if second < 0:
            minute = minute - 1
            if minute >= -1:
                second = second + 60      
            if minute < 0:
                hour = hour - 1
                if hour >= 0:
                    minute = minute + 60
        if hour <= 0 and minute <= 0 and second <= 0:
            x = x + 1