Python Stopwatch Example
Build a simple stopwatch in Python that measures elapsed time. This example uses the time module and shows, step by step, how to record a start time, record an end time, and calculate the difference.
If you are new to timing code in Python, this is a good first example because it uses only a few lines of code and one standard library module.
Quick example
import time
input("Press Enter to start the stopwatch...")
start_time = time.time()
input("Press Enter to stop the stopwatch...")
end_time = time.time()
elapsed = end_time - start_time
print(f"Elapsed time: {elapsed:.2f} seconds")
This is the simplest stopwatch version. It starts when you press Enter and stops when you press Enter again.
What this example does
This stopwatch script:
- Measures how much time passes between two user actions
- Uses
time.time()to get the current time in seconds - Calculates elapsed time by subtracting the start time from the end time
- Prints the result in a readable format
How the basic stopwatch works
The basic idea is simple:
- Ask the user to press Enter to begin
- Store the current time in a variable like
start_time - Ask the user to press Enter again to stop
- Store the current time in
end_time - Subtract
start_timefromend_time - Display the result with formatting such as
.2ffor two decimal places
Here is the full example again:
import time
input("Press Enter to start the stopwatch...")
start_time = time.time()
input("Press Enter to stop the stopwatch...")
end_time = time.time()
elapsed = end_time - start_time
print(f"Elapsed time: {elapsed:.2f} seconds")
Example output:
Press Enter to start the stopwatch...
Press Enter to stop the stopwatch...
Elapsed time: 3.47 seconds
Code walkthrough points
import time
import time
This line gives your program access to Python's time-related functions.
If you want a broader introduction, see the Python time module overview.
input() pauses the program
input("Press Enter to start the stopwatch...")
The input() function waits until the user presses Enter. That makes it useful for a simple start-and-stop stopwatch.
If you need help with this part, see how to get user input in Python.
time.time() gets the current time
start_time = time.time()
time.time() returns the current Unix timestamp as a floating-point number. That means the value includes fractions of a second.
Later, the script does the same thing again:
end_time = time.time()
You can learn more here: time.time() explained.
Subtracting timestamps gives elapsed time
elapsed = end_time - start_time
This is the key step.
start_timeis the moment the stopwatch beganend_timeis the moment it stopped- The difference is the elapsed time in seconds
f-strings make output easier to read
print(f"Elapsed time: {elapsed:.2f} seconds")
This uses an f-string to insert the value of elapsed into the text.
The .2f part means:
- show the number as a floating-point value
- keep 2 digits after the decimal point
So a value like 3.472891 becomes 3.47.
Small improvements to show
Once the basic version works, you can improve it in a few useful ways.
Round the output to 2 decimal places
The first example already does this with:
print(f"Elapsed time: {elapsed:.2f} seconds")
Without formatting, the result may show too many decimal places.
Show minutes and seconds
For longer times, minutes and seconds are easier to read than a decimal number.
import time
input("Press Enter to start the stopwatch...")
start_time = time.time()
input("Press Enter to stop the stopwatch...")
end_time = time.time()
elapsed = end_time - start_time
minutes = int(elapsed // 60)
seconds = elapsed % 60
print(f"Elapsed time: {minutes} minute(s) and {seconds:.2f} second(s)")
Example output:
Elapsed time: 1 minute(s) and 12.35 second(s)
Handle KeyboardInterrupt
If the user stops the program with Ctrl+C, Python raises a KeyboardInterrupt. You can handle that so the program exits more cleanly.
import time
try:
input("Press Enter to start the stopwatch...")
start_time = time.time()
input("Press Enter to stop the stopwatch...")
end_time = time.time()
elapsed = end_time - start_time
print(f"Elapsed time: {elapsed:.2f} seconds")
except KeyboardInterrupt:
print("\nStopwatch cancelled.")
Wrap the logic in a function
Putting the code in a function makes it easier to reuse later.
import time
def run_stopwatch():
input("Press Enter to start the stopwatch...")
start_time = time.time()
input("Press Enter to stop the stopwatch...")
end_time = time.time()
elapsed = end_time - start_time
print(f"Elapsed time: {elapsed:.2f} seconds")
run_stopwatch()
This is a good step if you want to turn the stopwatch into a larger program.
Beginner mistakes to watch for
Common beginner mistakes with this example include:
- Forgetting to import the
timemodule - Using
time.sleep()instead oftime.time()for measuring elapsed time - Trying to subtract strings instead of numeric time values
- Overwriting variable names like
timewith your own variable
time.sleep() is not the same thing
A very common confusion is mixing up time.sleep() and time.time().
time.time()gets the current timetime.sleep()pauses the program
So this is for measurement:
now = time.time()
And this is for pausing:
time.sleep(2)
If you want to understand the difference better, see time.sleep() explained.
Common mistakes and debugging
Here are some common causes of problems:
NameErroriftimeis used withoutimport timeAttributeErrorif a variable namedtimereplaces the module name- Confusion between pausing code and measuring time
- Incorrect indentation when placing code inside a function or loop
For example, this causes a problem because time is no longer the module:
import time
time = "hello"
print(time.time())
Python will fail because time now refers to a string, not the module.
Helpful debugging commands
You can use these commands or print statements while testing:
python stopwatch.py
print(start_time)
print(end_time)
print(elapsed)
You can also trace the script step by step:
python -m trace --trace stopwatch.py
If you are new to debugging, see the beginner guide to debugging Python code.
FAQ
Is this a real stopwatch that updates on the screen?
No. This basic version only measures the time between start and stop. A live updating stopwatch would need a loop and repeated output.
Why use time.time() here?
It returns the current time in seconds, so you can subtract two values to find elapsed time.
Can I show minutes and seconds instead of decimal seconds?
Yes. You can divide the elapsed time into minutes and remaining seconds before printing.
What is the difference between this and time.sleep()?
time.sleep() pauses the program. It does not calculate elapsed time for you.
See also
- Python time module overview
- time.time() explained
- time.sleep() explained
- How to get user input in Python
- How to debug Python code
- Python countdown timer example
- Python timer script example
Try improving this basic stopwatch next by adding a live display, formatting the result as minutes and seconds, or turning the code into a reusable function.