Two small tools from the time module: a countdown timer that waits one second between numbers, and a stopwatch that measures how long something took.
The program
import time def countdown(seconds, tick=1.0): for remaining in range(seconds, 0, -1): minutes, secs = divmod(remaining, 60) print(f"{minutes:02}:{secs:02}") time.sleep(tick) print("Time's up!") # tick=0.02 keeps this example fast; leave out tick for a real 1-second timer countdown(5, tick=0.02)
00:05 00:04 00:03 00:02 00:01 Time's up!
How it works
range(seconds, 0, -1)counts down: 5, 4, 3, 2, 1. The third number,-1, is the step.divmod(remaining, 60)gives two answers at once: the whole minutes and the seconds left over.divmod(125, 60)is(2, 5).:02in the f-string pads the number to two digits with a leading zero, so 5 prints as05.time.sleep(tick)pauses the program for that many seconds.
A stopwatch
To measure time, read a clock before and after, and subtract. time.perf_counter() is the clock made for this: it is the most precise one, and it is not affected if the computer's clock is changed while your program runs.
import time start = time.perf_counter() time.sleep(0.1) # stands in for the work you want to time elapsed = time.perf_counter() - start print(f"Elapsed: {elapsed:.1f} seconds")
Elapsed: 0.1 seconds
The real elapsed time is a little more than 0.1 seconds, and it changes slightly every run. :.1f rounds it to one decimal place. For a stopwatch you control with the keyboard, read the clock after one input("Press Enter to start") and again after a second input("Press Enter to stop").