Sai A Sai A
Updated date Jan 14, 2024
In this blog, we will learn how to build a simple stopwatch from scratch. This blog guides you through two methods using built-in modules: 'time' and 'datetime.'

Introduction:

In this blog, we will explore how to build a simple stopwatch using Python. Whether you are a beginner or an experienced developer, this project is a great way to enhance your Python skills while creating a practical tool.

Method 1: Using time Module

Let's start with a simple approach using Python's built-in time module. This method involves recording the starting time, displaying elapsed time, and stopping the stopwatch when needed.

import time

def simple_stopwatch():
    input("Press Enter to start the stopwatch.")
    start_time = time.time()
    
    try:
        while True:
            elapsed_time = time.time() - start_time
            print(f"\rElapsed Time: {elapsed_time:.2f} seconds", end="")
            time.sleep(1)
    except KeyboardInterrupt:
        print("\nStopwatch stopped.")
        pass

if __name__ == "__main__":
    simple_stopwatch()

Output:

Press Enter to start the stopwatch.
Elapsed Time: 5.00 seconds
Stopwatch stopped.
  • The program begins by prompting the user to press Enter to start the stopwatch.
  • It records the starting time using time.time().
  • Inside the try block, the program calculates the elapsed time and displays it continuously with the help of time.sleep(1) to update the display every second.
  • The stopwatch can be stopped by pressing Ctrl+C, which raises a KeyboardInterrupt exception, allowing the program to print a message and gracefully exit.

Method 2: Using datetime Module

The datetime module provides another way to work with time, offering more flexibility in formatting and handling time-related operations.

from datetime import datetime
import time

def simple_stopwatch_datetime():
    input("Press Enter to start the stopwatch.")
    start_time = datetime.now()
    
    try:
        while True:
            elapsed_time = datetime.now() - start_time
            print(f"\rElapsed Time: {elapsed_time}", end="")
            time.sleep(1)
    except KeyboardInterrupt:
        print("\nStopwatch stopped.")
        pass

if __name__ == "__main__":
    simple_stopwatch_datetime()

Output:

Press Enter to start the stopwatch.
Elapsed Time: 0:00:05.000000
Stopwatch stopped.
  • Similar to the previous method, the program starts by prompting the user to press Enter.
  • It records the starting time using datetime.now().
  • Inside the loop, it calculates the elapsed time, and the display shows the time in the format days:hours:minutes:seconds.microseconds.
  • The stopwatch can be stopped by pressing Ctrl+C, leading to a graceful exit.

Conclusion:

In this blog, we have discussed two simple methods to create a stopwatch in Python. The first method used the time module, while the second used the datetime module for a more versatile time representation. Python's built-in modules make it easy to work with time, allowing you to create practical tools like stopwatches efficiently.

Comments (0)

There are no comments. Be the first to comment!!!