You could just take the remainder when dividing by 65535 with the modulo operator %:

In [114]: int(time.perf_counter()*1000) % 65535
Out[114]: 29548

If you also are interested to know how many times the timer has been resetted, you can use divmod:

In [115]: divmod(int(time.perf_counter()*1000),65535)
Out[115]: (31, 30036)
Answer from Niko Fohr on Stack Overflow
🌐
Real Python
realpython.com › python-timer
Python Timer Functions: Three Ways to Monitor Your Code – Real Python
December 8, 2024 - On the other hand, when you call .stop(), you first check that the Python timer is running. If it is, then you calculate the elapsed time as the difference between the current value of perf_counter() and the one that you stored in ._start_time. Finally, you reset ._start_time so that the timer can be restarted, and print the elapsed time.
🌐
Reddit
reddit.com › r/learnpython › created my first tkinter project: count-down timer : reset/pause and resume buttons.
r/learnpython on Reddit: Created My First Tkinter Project: Count-Down Timer : Reset/pause and resume buttons.
March 20, 2023 -

Been learning functions and how to add them to buttons and working with time in general. So wanted to create a little project that will test me on those areas.

import tkinter as tk
from tkinter import *
import time


root = Tk()
root.title('                                      COUNT-DOWN TIMER')
#root.geometry("800x400")
root['background']='#2F4F4F'

total_time = 0

rest = 0

pause = "No"

#####ADD/MINUS/RESET FUNCTIONS

def add_time_hour():
    global total_time
    total_time += 3600
    countdown_label.config(text=f"{total_time//3600:02}:{(total_time//60)%60:02}:{total_time%60:02}",fg = '#00FF00',font=("Arial", 24))

def add_time_min():
    global total_time
    total_time += 60
    countdown_label.config(text=f"{total_time//3600:02}:{(total_time//60)%60:02}:{total_time%60:02}",fg= "#00FF00",font=("Arial", 24))

def add_time_sec():
    global total_time
    total_time += 1
    countdown_label.config(text=f"{total_time//3600:02}:{(total_time//60)%60:02}:{total_time%60:02}",fg= "#00FF00",font=("Arial", 24))

def add_rest_min():
    global rest
    rest += 60
    rest_label.config(text=f"{(rest // 3600) % 3600:02}:{(rest // 60) % 60:02}:{rest % 60:02}",fg= "#00FF00",font=("Arial", 24))

def reset():
    global total_time, rest,pause
    pause = "No"
    total_time = 0
    rest = 0
    countdown_label.config(text=f"{total_time//3600:02}:{(total_time//60)%60:02}:{total_time%60:02}",fg= "#00FF00",font=("Arial", 24))
    rest_label.config(text=f"{(rest // 3600) % 3600:02}:{(rest // 60) % 60:02}:{rest % 60:02}",fg= "#00FF00",font=("Arial", 24))

############TIME FUNCTIONS#############################################

def countdown():
    global total_time,rest, pause
    if total_time > 0 and pause == "No":
        total_time -= 1
        countdown_label.config(text=f"{(total_time // 3600) % 3600:02}:{(total_time // 60) % 60:02}:{total_time % 60:02}",fg="#00FF00", font=("Arial", 24))
        root.after(1000,countdown)
        if total_time == 0:
            countdown_label.config(
                text=f"{(total_time // 3600) % 3600:02}:{(total_time // 60) % 60:02}:{total_time % 60:02}", fg="red",
                font=("Arial", 24))

    elif total_time == 0 and rest > 0 and pause == "No":
        rest -= 1
        rest_label.config(text=f"{(rest// 3600) % 3600:02}:{(rest // 60) % 60:02}:{rest % 60:02}", fg="#00FF00", font=("Arial", 24))
        root.after(1000,countdown)
        if rest == 0:
            rest_label.config(text=f"{(rest // 3600) % 3600:02}:{(rest // 60) % 60:02}:{rest % 60:02}", fg="red",
                              font=("Arial", 24))

def countdown_pause():
    global pause
    pause = "Yes"

def countdown_unpause():
    global pause
    pause = "No"
    countdown()

#############LABELS####################
countdown_label = tk.Label(text = "00:00:00",fg="#00FF00",bg='#2F4F4F', font=("Arial", 24))
countdown_label.grid(row= 0, column = 2, columnspan=2)

countdown_label_title = tk.Label(text = "RUNNING: ",fg="#00FF00",bg='#2F4F4F', font=("Arial", 24))
countdown_label_title.grid(row= 0, column = 0, columnspan=2)

rest_label = tk.Label(text = "00:00:00", fg= "#00FF00",bg='#2F4F4F',font=("Arial", 24))
rest_label.grid(row= 1, column = 2, columnspan=2)

rest_label_title = tk.Label(text = "RESTING: ",fg="#00FF00",bg='#2F4F4F', font=("Arial", 24))
rest_label_title.grid(row= 1, column = 0, columnspan= 2)

#BUTTONS###
add_button = tk.Button(root, text="START", command=countdown, bg='#36648B', font=("Arial", 18))
add_button.grid(row= 3, column = 1)

add_button = tk.Button(root, text="+HOUR", command=add_time_hour, bg='#36648B', font=("Arial", 18))
add_button.grid(row= 2, column = 0)

add_button = tk.Button(root, text="+MNTS", command=add_time_min, bg='#36648B', font=("Arial", 18))
add_button.grid(row= 2, column = 1)

add_button = tk.Button(root, text="+SCND", command=add_time_sec, bg='#36648B', font=("Arial", 18))
add_button.grid(row= 2, column = 2)

add_button = tk.Button(root, text="RESET ", command=reset, bg='#36648B', font=("Arial", 18))
add_button.grid(row= 3, column = 0)

add_button = tk.Button(root, text="RST-MIN", command=add_rest_min, bg='#36648B', font=("Arial", 18))
add_button.grid(row= 2, column = 3)

add_button = tk.Button(root, text="PAUSE", command=countdown_pause, bg='#36648B', font=("Arial", 18))
add_button.grid(row= 3, column = 2)

add_button = tk.Button(root, text="RESUME", command=countdown_unpause, bg='#36648B', font=("Arial", 18))
add_button.grid(row= 3, column = 3)

root.mainloop()
Discussions

Resetting time.clock() in Python - Stack Overflow
I start a timer, calculate elapsed ... and then reset elapsed to 0 so "MOTION" only displays every 10 seconds. For some reason, it doesn't work: MOTION does initially get displayed after 10 seconds, but after that, it keeps getting displayed on every iteration. What did I do wrong? ... DeprecationWarning: time.clock has been deprecated in Python 3.3 and will be removed from Python 3.8: use time.perf_counter or ... More on stackoverflow.com
🌐 stackoverflow.com
python - how can I reset the counter? - Stack Overflow
I want the counter to reset to zero after the 30-second timer ends so if the user gets it wrong 3 times they can retry after the time is up. I'm using python btw here is the section I need help with: More on stackoverflow.com
🌐 stackoverflow.com
Reset counter to zero if different day - Python - Stack Overflow
Just wondering if there is a work around this process or is there a python library that can handle this type of situation. Your suggestions will be appreciated! ... You could assign the counter outside of that function and send it as a parameter, that way you don't overwrite it every single time ... More on stackoverflow.com
🌐 stackoverflow.com
May 10, 2018
python - How to set the counter to 0 again after button click? - Stack Overflow
You question is unclear. As @tobias_k said you are already doing something on button click. Are you asking for a timer that will set the counter to zero if you wait to long to click the button? Or for another button that will reset the counter? More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python
docs.python.org › 3 › library › time.html
time — Time access and conversions
Similar to thread_time() but return time as nanoseconds. Added in version 3.7. ... Reset the time conversion rules used by the library routines. The environment variable TZ specifies how this is done.
🌐
GitHub
gist.github.com › aeroaks › ac4dbed9c184607a330c
Reset Timer in Python · GitHub
Reset Timer in Python. GitHub Gist: instantly share code, notes, and snippets.
🌐
Python
docs.python.org › 3.3 › library › time.html
16.3. time — Time access and conversions — Python 3.3.7 documentation
A tuple of two strings: the first is the name of the local non-DST timezone, the second is the name of the local DST timezone. If no DST timezone is defined, the second string should not be used. ... Resets the time conversion rules used by the library routines.
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 70917318 › how-can-i-reset-the-counter
python - how can I reset the counter? - Stack Overflow
Try again.') for i in range(_t, 0, -1): mins, secs = divmod(i, 60) timer = '{:02d}:{:02d}'.format(mins, secs) print(f'\ryou can try again in : {timer}', end='') time.sleep(1) print('\r', end='') login(_t) t = 3 login(t)
🌐
Python Forum
python-forum.io › thread-14990.html
Reset counter when the day turns over
I want to monitor an event's and store value in counter and when the day turns over, it resets the counter to zero. Here is a example Day: 28 Count: 0 Day: 28 Count: 1 Day: 28 Count: 2 ... ..... Day: 28 Count: 123 Day: 29 Count: 0 Day: 29 Count: ...
🌐
PyPI
pypi.org › project › count-timer
count-timer · PyPI
July 18, 2022 - reset(): reset() -> None Puts the timer back in its original state when first created (paused / not yet started) These details have been verified by PyPI · JavaJeff · These details have not been verified by PyPI · Homepage · License: MIT License (MIT) Author: Jeff Wright · Tags python , counter , timer , count-timer , count_timer ·
      » pip install count-timer
    
Published   Jul 19, 2022
Version   0.3.8
🌐
Quora
quora.com › How-do-you-reset-a-counter-in-Python
How to reset a counter in Python - Quora
Answer (1 of 3): lets say you have a counter, in a variable x * At the start x is reseted [code]x = 0 [/code]Now we want to iterate a list and reset that counter if we find something specific in it * “The list” [code]my_list = ["John", "James", "Maria", "Nick", "Mike"] [/code] * “The ...
🌐
Stack Overflow
stackoverflow.com › questions › 50259064 › reset-counter-to-zero-if-different-day-python
Reset counter to zero if different day - Python - Stack Overflow
May 10, 2018 - It has a __next__ method that returns the next number so the calling code only needs to call next(counter). It also has an __iter__ method so it can be used in for loops. You need to provide a function to get the current (date_getter) time when creating an instance.
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › programming › python
A resetable background timer? - Raspberry Pi Forums
set a timer counter to zero to begin with. Increment the timer at regular intervals, when the timer reaches a value it has "timed out". On an "activity" event reset the timer counter value to zero.
🌐
GeeksforGeeks
geeksforgeeks.org › python › time-perf_counter-function-in-python
time.perf_counter() function in Python - GeeksforGeeks
January 13, 2026 - The time.perf_counter() function returns a high-resolution timer value used to measure how long a piece of code takes to run.
Top answer
1 of 2
55

If you just want to measure the elapsed wall-clock time between two points, you could use time.time():

import time

start = time.time()
print("hello")
end = time.time()
print(end - start)

This gives the execution time in seconds.

Another option since 3.3 might be to use perf_counter or process_time, depending on your requirements. Before 3.3 it was recommended to use time.clock . However, it is currently deprecated:

On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name.

On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.

Deprecated since version 3.3: The behaviour of this function depends on the platform: use perf_counter() or process_time() instead, depending on your requirements, to have a well defined behaviour.

2 of 2
2

Why do you need a counter? Just initialise start_time variable to None in the beginning, then in your if-block you check whether it is set, if it isn't you set it to time.time(). In the else-block set end_time to time.time() again and calculate the difference.

EDIT

I don't know what the layout of the rest of your application, you have to initialise start_time = None somewhere outside of this update function. You would need to set it for each user, I will assume it is stored as user.start_time, but again, this is dependent on the structure of your app. Then your function could become this:

    @bot.event
    async def on_voice_state_update(before, after):

        if after.voice.voice_channel:
            if not user.start_time:  # this was set to None somewhere else
                user.start_time = time.time()
            # import datetime from datetime at the top of your file
            timestrr = datetime.from_timestamp(user.start_time).strftime("%d.%m.%Y-%H:%M:%S")
            voicezeit(after.id, timestrr)
        else:
             end_time = time.time()
             voice_chat_time = end_time - after.user.start_time
🌐
DEV Community
dev.to › blackmare01wolf › creating-a-countdown-timer-with-tkinter-in-python-4i3j
Creating a Countdown Timer with Tkinter in Python - DEV Community
April 19, 2025 - 7. Reset Timer: Clears the countdown and resets display. Now that we have a basic countdown timer, let’s add some enhancements: Add a Pause Button: Allow users to pause and resume the countdown. Custom Timer Settings: Background color, fonts, or sound alerts. Better Error Handling: Restrict input to valid integers only. By following this guide, you've created a simple yet functional countdown timer using Python and Tkinter.
Top answer
1 of 2
1

I would suggest using the time module for something like this:

from time import time, sleep
from datetime import datetime, timedelta

nowtime = time()

#Put your script here
x = 1
for k in range(1000):
        x+=1
        sleep(0.01)

sec = timedelta(seconds=int(time()-nowtime))
d = datetime(1,1,1)+sec

print("DAYS:HOURS:MIN:SEC")
print("%d:%d:%d:%d" % (d.day-1, d.hour, d.minute, d.second))

This assigns the time in seconds at the beginning to a variable, and after the main script has finished, it subtracts the previous time from the current time and formats it in days, hours, minutes, and seconds.

Here is it running:

bash-3.2$ python timing.py
DAYS:HOURS:MIN:SEC
0:0:0:10
bash-3.2$ 

You could also use the Threading module, which has a built-in cancel method:

>>> import threading
>>> def hello():
...     print "This will print after a desired period of time"
... 
>>> timer = threading.Timer(3.0, hello)
>>> timer.start() #After 3.0 seconds, "This will print after a desired period of time" will be printed
>>> This will print after a desired period of time

>>> timer.start()
>>> timer = threading.Timer(3.0, hello)
>>> timer.start()
>>> timer.cancel()
>>> 
2 of 2
1

Python actually has a class for this, which includes a cancel method: threading.Timer. It seems to be close enough to the Java Timer class for your needs (The Java Timer also runs in background thread). Here's the example usage from the docs:

def hello():
    print "hello, world"

t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed

Edit:

The problem with your updated code is that you're trying to use the same Timer object more than once. That may be possible in the Java implementation, but in Python you can't reuse a Thread object (Timer is a Thread subclass). You'll need to create a new Timer object after you join() it. Like this:

t = threading.Timer(5.0, countdown)   
def enter():
    global t  # You need this to tell Python that you're going to change the global t variable. If you don't do this, using 't = ..' will just create a local t variable.
    if int(Variable.count == 1):
        print("Entered")
        t.start()
    else:
        print("Entered +1")
        t.cancel()
        t.join()         # here you block the main thread until the timer is completely stopped
        t = threading.Timer(5.0, countdown)
        t.start()
🌐
MicroPython
docs.micropython.org › en › latest › library › pyb.Timer.html
class Timer – control internal timers — MicroPython latest documentation
The rate at which it counts is the peripheral clock frequency (in Hz) divided by the timer prescaler. When the counter reaches the timer period it triggers an event, and the counter resets back to zero. By using the callback method, the timer event can call a Python function.
Top answer
1 of 1
1

This is expected as time is passed "by value" (you copy the content of the variable "into the function").

Perhaps you need to change your approach to "timer" as there appears to be no equivalent to "get_timer" to get the time left before the event is fired.

I'm not exactly sure how your whole game is developed, but you probably need to track the time yourself so that you can check the time left.

I'm not fluent in pygame, but, based on your previous question and pygame's documentation, perhaps something like this would work:

...

class Singlebullet(object):

    def __init__(self):
        self.img = pygame.image.load(r'C:\Users\Salem\Documents\MyGame1\bullet.png')
        self.state = 'ready'
        self.speed = 0
        self.firerate = 700 # assuming ms
        # this is new:
        self.bullet_time_left = self.firerate
        self.clock = pygame.time.Clock()
    
    def shoot(self):
        if current_bullet_type == 'single':
            if self.state == 'ready':
                self.x = myplane.x + 71 
                self.y = myplane.y 
            elif self.state == 'fire': # use elif instead of if
                self.speed = -13
                
                
            for event in events:
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE and self.state == 'ready':
                        self.clock = pygame.time.Clock()
                        self.bullet_time_left = self.firerate
                        self.state = 'fire'
                        
            delay = self.clock.tick()
            if self.state == 'fire':
                self.bullet_time_left -= delay
                if self.bullet_time_left <= 0:
                    self.bullet_time_left = self.firerate
                    self.state = 'ready'
                else:
                    reload_time = myfont.render(self.bullet_time_left, True, 'black')
                    MyScrollingScreen.blit(reload_time, (670, 650))
                    

            MyScrollingScreen.blit(self.img, (self.x, self.y))
            
            self.y += self.speed
s1 = Singlebullet()
...
while running:
    ...
    s1.shoot()
    ...

That's the gist of it. You start a "Clock" when you fire the bullet; each update, you "update" it via it's tick() method to check how much time has passed since the last "tick()". You remove that time from the "time left"; once that counter gets below 0, you know that you're done and should clean it up. You have access to the time left so you can use it to update your label.

You'll probably want to rearrange some of what I wrote to suit your needs.


As I mentioned, I'm not fluent with pygame, and so maybe someone else has a better approach to propose.