Stopwatch in Python
In Python you can use the time module to wait (you can also get the time and date). To be explicit, the time module provides various time-related functions.
This is very useful for many applications. If you make a game, it should not update every millisecond. If you make weather station software, it makes no sense to update in such a short time. For an alarm clock app, you need it to wait.
Lets say you want to make a stopwatch, without the program pausing there would be no way to create one.
Sleep function
The module time has a function named sleep, which pauses the program (it complete freezes the program).
This waits for t number of seconds. Consider this program which waits for one second before it outputs the next word.
Stopwatch
So you can use the time.sleep() function to pause the program. But a stopwatch doesn’t have a limit, it needs to go on. For that, you can use a while loop. Then you can use Ctrl+c to exit the program.
If you run the above program it outputs:
Until you press Ctrl+c. Now it needs to count seconds, you can use time.time() to get the current time.
The example below will output every second passed until Ctrl+C is passed.
Formatting
To format it you can use f-strings with two digits. With a simple calculation you can get the minutes and seconds.
Секундомер в Pythonе [дубликат]
Как реализовать секундомер в питоне? С таким кодом не всегда ловит одну секунду:
Output такой: 0 7.0 1 10.0 2 16.0 3 17.0 И вообше всегда разний.
Вы что-то такое хотели?
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.6.8.43486
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
How To Create A Stopwatch In Python
In this tutorial, we will be going through a fun program to create a stopwatch in python. For this, we will be using time.time() function from the time module.
A stopwatch essentially tells the time elapsed from start to stop.
time.time() in Python
We will be using time.time() function from the time module. Documentation is here.
time.time() function keeps the track of the number of seconds passed from the time the day began i.e. the epoch 00:00.
To use this function we will first import the time module into our code.
Time to create a stopwatch using Python
- We will import time module.
- The user will press Enter to start the stopwatch. At this point start_time is set using time.time(). So, at this point, start_time has the number of seconds passed since epoch when the clock is started.
- Now, the clock will run in the background.
- Now the user will press Enter again for stopping the stopwatch. At this point end_time is set using time.time(). So, at this point, end_time has the number of seconds passed since epoch when the clock is stopped.
- So, the time lapse can be calculated using the difference between end_time and start_time.
- time_lapsed has the value in seconds. We want the output in hours, minutes and seconds. To do this we will use the user-defined function time_convert().
- time_convert() will convert seconds into minutes by dividing the number of seconds by 60 and then the number of minutes divided by 60 is the number of hours.
- We are printing the Lapsed time also from inside time_convert().
Output
If 140 seconds have passed then the output will look like:
So, here it is. A very simple program to create a Stopwatch in Python.
10 responses to “How To Create A Stopwatch In Python”
Good day sir! Thankyou for this code you provided. It is very helpful.
But my problem here is that, I want to add a simple push button switch to turn on the stopwatch and then stop it again with it. But I dont know when to insert or even enter a code that will make the system work.
How would I make it so I can see the timer while it is going?
Hi Tyler, I was able to do so with this, but still working on it
Hope it helps
while True:
start_time=time.time()
while True:
end_time=time.time()
print(stopTime-startTime)
time.sleep(.1)
Use GUIZero in conjunction with this, a simple way to get a button to work with the stopwatch.
do u want it to print it or do u want to show it on the window screen?
Is there a way to save the times to view later? like when you open the program back up, it prints the last stopwatch times?
Yes There is, you can save the results into a file
Here is one of many ways how to do it: (It’ll work only on windows tho)
import os
import time
exist = os.system(“if exist stopwatch.txt echo 1”)
if exist == “1”:
lastsec = os.system(“type stopwatch.txt”)
lastsec = int(lastsec)
os.system(“del stopwatch.txt”)
print(“Last stopwatch:”)
time_convert(lastsec)
def time_convert(sec):
mins = sec // 60
sec = sec % 60
hours = mins // 60
mins = mins % 60
print(“Time Lapsed = <0>:<1>:<2>”.format(int(hours),int(mins),sec))
input(“Press Enter to start”)
start_time = time.time()
input(“Press Enter to stop”)
end_time = time.time()
time_lapsed = end_time – start_time
save = time_lapsed
time_convert(time_lapsed)
os.system(“echo %d > stopwatch.txt” % (int(save)))
here is my solution:
import tkinter as Tkinter
from datetime import datetime
import win32gui, win32con
the_program_to_hide = win32gui.GetForegroundWindow()
win32gui.ShowWindow(the_program_to_hide , win32con.SW_HIDE)
def counter_label(label):
global counter, h, m, s
def count():
global counter, h, m, s
if running:
s_h = h
s_m = m
s_s = s
if h < 10:
s_h = "0" + str(h)
if m < 10:
s_m = "0" + str(m)
if s = 60:
s = 0
m += 1
if m >= 60:
m = 0
h += 1
def Reset(label):
global counter, h, m, s
h = 0
m = 0
s = 0
if running==False:
string = “Hours: 00”
string2 = “Minutes: 00”
string3 = “Seconds: 00”
display=(string)
display2=(string2)
display3=(string3)
Stopwatch Using Python Tkinter

We are all familiar with the stopwatch. And, it is possible to create a Stopwatch Using Python. According to our information, the DateTime module is already available in Python. We can use that module to create a timer in Python. We are hoping that this content will be fantastic. You can use this as a primary-level Python mini-project. Click here for the complete source code. Let’s get started.
Implementation for Stopwatch Using Python in Tkinter
Step1. Importing libraries and initializing variables
To make a timer in Python, we must first import the Tkinter package. To obtain a time, import the DateTime module. Declaring the count as global and setting it to zero.
Step 2. Stopwatch Class
In Python code, create a stopwatch class. Create a function to conduct a reset action after creating a class. This function resets the timing to 00:00:00, akin to restarting the stopwatch.
Step 3. Start method for Stopwatch Using Python
To start the stopwatch, write a function called start. This feature is useful for starting the stopwatch.
Step 4. Stop method
To stop the stopwatch, we need a stop function. To conduct the stop operation in the stopwatch, we must write another function called to stop.
Step 5. Close method
When creating applications, always include an exit button. That will make an excellent first impression on your application. To conduct the exit procedure, we must develop a function called close. When we click the exit button, it will exit the application.
Step 6. Create the timer method
Create a timer function to run the stopwatch. I hope you saw that I named a functioning self.timer(). So, when the program sees that sentence, it will call this function and do the task specified in the timer function.
Step 7. Creating the init method for Stopwatch Using Python
Following that, we add an init function in this program, as well as a button for each operation. Furthermore, this function will invoke all of the functions. To improve our timer, we’re changing the backdrop colors of the letters.
Complete source code for Stopwatch using Python Tkinter
Output:

In this tutorial, we learned how to create a Stopwatch Using Python Tkinter. This article will be useful for all Python beginners. Learn it completely. Try to solve the code on your own. If you have any questions, please leave them in the comment section.