Python Tutorial (33) – Example: Implementing a stopwatch function

Time: Column:Python views:226

Stopwatch Function Using Python's time Module

The following example demonstrates how to create a stopwatch using Python's time module:

Example

import time

print('Press Enter to start the stopwatch, press Ctrl + C to stop.')

while True:
   input("")  # Wait for the user to press Enter to start timing
   start_time = time.time()  # Record the start time
   print('Stopwatch started...')

   try:
       while True:
           elapsed_time = round(time.time() - start_time, 0)  # Calculate the elapsed time
           print(f'Elapsed time: {elapsed_time} seconds', end="\r")  # Overwrite the previous output
           time.sleep(1)
   except KeyboardInterrupt:  # Catch the Ctrl + C interrupt signal
       end_time = time.time()  # Record the end time
       total_time = round(end_time - start_time, 2)
       print(f'\nStopwatch stopped, total time: {total_time} seconds')
       break

Output

Press Enter to start the stopwatch, press Ctrl + C to stop.

Stopwatch started...
^CElapsed time: 3.0 seconds
Stopwatch stopped, total time: 3.77 seconds

This script starts timing when the user presses Enter and stops when Ctrl + C is pressed. It continuously displays the elapsed time until the user interrupts the process. The final output shows the total time in seconds.