create stopwatch in python using time

In this python example, you will learn to work with time library and create simple stop watch.

Generally, we are all aware of the stopwatch. We can create a stopwatch in python with more than one method. In this example we will create stopwatch with time module.

Here, We will import time module to get time object, then create infinite loop that starts with enter key and can only stop by user with ctrl + c once it started.

Example : Stopwatch Program in Python

    
#Python program for Stopwatch
import time
while True:
    try:
        input("Press Enter to continue and ctrl+C to exit the stopwatch")
        start_time=time.time()
        print("Stopwatch has started")
        while True:
            print("Time elapsed:",round(time.time()-start_time,0),'secs',end='\n')
            time.sleep(1)
    except KeyboardInterrupt:
        print("Timer has stopped")
        end_time=time.time()
        print("The time elapsed:",round(end_time-start_time,2),'secs')
        break
   

Output :

    
Press Enter to continue and Ctrl+C to exit the stopwatch
Stopwatch has started
Time elapsed: 0.0 secs
Time elapsed: 1.0 secs
Time elapsed: 2.0 secs
Time elapsed: 3.0 secs
Time elapsed: 4.0 secs
Time elapsed: 5.0 secs
Timer has stopped
The time elapsed: 6.13 secs
    

Share your thoughts

Ask anything about this examples