You have two options; your code doesn't work because you are trying to reset the clock but instead you reset elapsed, which does nothing.

Using modulo division.

start = time.clock()
while True:
  elapsed = (time.clock() - start)
  if int(elapsed) % 10:
    print("MOTION")

Resetting the clock.

start = time.clock()
while True:
  elapsed = (time.clock() - start)
  if elapsed >= 10:
    print("MOTION")
    start = time.clock()
Answer from Evan Weissburg on Stack Overflow
๐ŸŒ
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.
Discussions

How to reset pygames time.
Why do you need this? Sounds like you could just make your own timer variable where every frame, you add the amount of time that has passed since the last frame. Probably not as exact as time.get_ticks, but I can't think of a reason why you would need it that precise. More on reddit.com
๐ŸŒ r/pygame
20
3
January 13, 2020
Python time.clock() - reset clock value with threads - Stack Overflow
Is starting and killing threads supposed to restart the time.clock() as well? It doesn't seem to be working right now. If not, is the only solution to re-launch the entire executable? ... A thread is not a process, so, no. (As a minor point, you can't kill a thread in Python, you can only ask it to exit. Killing threads through other means, where such means even exist, is likely to leave Python in a bad state.) The question is why you want to reset ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
April 20, 2013
python - Resetting time.clock() - Stack Overflow
I'm writing a basic game where you use the mouse to dodge stars, but I can't get a certain part to work properly. I'm trying to make it so that after 10 seconds of playing you beat the stage and i... More on stackoverflow.com
๐ŸŒ stackoverflow.com
June 6, 2013
Python module to change system date and time - Stack Overflow
How can I change System Date, Time, Timezone in Python? Is there any module available for this? I don't want to execute any system commands I want one common solution, which should work on both Un... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
GitHub
gist.github.com โ€บ aeroaks โ€บ ac4dbed9c184607a330c
Reset Timer in Python ยท GitHub
Reset Timer in Python. GitHub Gist: instantly share code, notes, and snippets.
๐ŸŒ
ActiveState
code.activestate.com โ€บ recipes โ€บ 577407-resettable-timer-class-a-little-enhancement-from-p
Resettable Timer class (a little enhancement from python builtin Timer class) ยซ Python recipes ยซ ActiveState Code
A more simple resettable timer class, by adding few logic from python builtin Timer code. the print statement in each function call is for debugging purposes only, to show if it works.
๐ŸŒ
PyPI
pypi.org โ€บ project โ€บ resettabletimer
Client Challenge
JavaScript is disabled in your browser ยท Please enable JavaScript to proceed ยท A required part of this site couldnโ€™t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
๐ŸŒ
YouTube
youtube.com โ€บ the python oracle
Python timer start and reset - YouTube
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn--Music by Eric Matyashttps://www.soundimage.orgTrack title: Darkness...
Published ย  January 2, 2023
Views ย  322
Find elsewhere
Top answer
1 of 6
38
import sys
import datetime

time_tuple = ( 2012, # Year
                  9, # Month
                  6, # Day
                  0, # Hour
                 38, # Minute
                  0, # Second
                  0, # Millisecond
              )

def _win_set_time(time_tuple):
    import pywin32
    # http://timgolden.me.uk/pywin32-docs/win32api__SetSystemTime_meth.html
    # pywin32.SetSystemTime(year, month , dayOfWeek , day , hour , minute , second , millseconds )
    dayOfWeek = datetime.datetime(time_tuple).isocalendar()[2]
    pywin32.SetSystemTime( time_tuple[:2] + (dayOfWeek,) + time_tuple[2:])


def _linux_set_time(time_tuple):
    import ctypes
    import ctypes.util
    import time

    # /usr/include/linux/time.h:
    #
    # define CLOCK_REALTIME                     0
    CLOCK_REALTIME = 0

    # /usr/include/time.h
    #
    # struct timespec
    #  {
    #    __time_t tv_sec;            /* Seconds.  */
    #    long int tv_nsec;           /* Nanoseconds.  */
    #  };
    class timespec(ctypes.Structure):
        _fields_ = [("tv_sec", ctypes.c_long),
                    ("tv_nsec", ctypes.c_long)]

    librt = ctypes.CDLL(ctypes.util.find_library("rt"))

    ts = timespec()
    ts.tv_sec = int( time.mktime( datetime.datetime( *time_tuple[:6]).timetuple() ) )
    ts.tv_nsec = time_tuple[6] * 1000000 # Millisecond to nanosecond

    # http://linux.die.net/man/3/clock_settime
    librt.clock_settime(CLOCK_REALTIME, ctypes.byref(ts))


if sys.platform=='linux2':
    _linux_set_time(time_tuple)

elif  sys.platform=='win32':
    _win_set_time(time_tuple)

I don't have a windows machine so I didn't test it on windows... But you get the idea.

2 of 6
9

The tMC's answer seems great. However, it was not working for me properly. I figured out it needed some updates, for both Linux and Windows + python 3. Here is my updated module:

import sys
from _datetime import datetime

time_tuple = (2012,  # Year
              9,  # Month
              6,  # Day
              0,  # Hour
              38,  # Minute
              0,  # Second
              0,  # Millisecond
              )


def _win_set_time(time_tuple):
    import win32api
    dayOfWeek = datetime(*time_tuple).isocalendar()[2]
    t = time_tuple[:2] + (dayOfWeek,) + time_tuple[2:]
    win32api.SetSystemTime(*t)


def _linux_set_time(time_tuple):
    import subprocess
    import shlex

    time_string = datetime(*time_tuple).isoformat()

    subprocess.call(shlex.split("timedatectl set-ntp false"))  # May be necessary
    subprocess.call(shlex.split("sudo date -s '%s'" % time_string))
    subprocess.call(shlex.split("sudo hwclock -w"))


if sys.platform == 'linux2' or sys.platform == 'linux':
    _linux_set_time(time_tuple)

elif sys.platform == 'win32':
    _win_set_time(time_tuple)

For Linux read the following answer: Set the hardware clock in Python?

๐ŸŒ
Psychopy
psychopy.org โ€บ api โ€บ core.html
psychopy.core - basic functions (clocks etc.) โ€” PsychoPy v2025.2.4
Reset the time on the clock. ... t (float, int or None) โ€“ With no args (None), time will be set to the time used for last reset (or start time if no previous resets).
๐ŸŒ
Saturn Cloud
saturncloud.io โ€บ blog โ€บ how-to-reset-the-time-part-of-a-pandas-timestamp-in-python
How to Reset the Time Part of a Pandas Timestamp in Python | Saturn Cloud Blog
October 4, 2023 - In this article, weโ€™ve explained how to reset the time part of a Pandas timestamp in Python. Weโ€™ve seen that we can use the replace() method of the Timestamp class to replace the hour, minute, and second parts of the timestamp with new values.
๐ŸŒ
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.
๐ŸŒ
MicroPython
docs.micropython.org โ€บ en โ€บ latest โ€บ library โ€บ time.html
time โ€“ time related functions โ€” MicroPython latest documentation
Set manually by a user on each power-up (many boards then maintain RTC time across hard resets, though some may require setting it again in such case).
Top answer
1 of 6
13

The freezegun package was made specifically for this purpose. It allows you to change the date for code under test. It can be used directly or via a decorator or context manager. One example:

from freezegun import freeze_time
import datetime

@freeze_time("2012-01-14")
def test():
    assert datetime.datetime.now() == datetime.datetime(2012, 1, 14)

For more examples see the project: https://github.com/spulec/freezegun

2 of 6
12

Monkey-patching time.time is probably sufficient, actually, as it provides the basis for almost all the other time-based routines in Python. This appears to handle your use case pretty well, without resorting to more complex tricks, and it doesn't matter when you do it (aside from the few stdlib packages like Queue.py and threading.py that do from time import time in which case you must patch before they get imported):

>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2010, 4, 17, 14, 5, 35, 642000)
>>> import time
>>> def mytime(): return 120000000.0
...
>>> time.time = mytime
>>> datetime.datetime.now()
datetime.datetime(1973, 10, 20, 17, 20)

That said, in years of mocking objects for various types of automated testing, I've needed this approach only very rarely, as most of the time it's my own application code that needs the mocking, and not the stdlib routines. After all, you know they work already. If you are encountering situations where your own code has to handle values returned by library routines, you may want to mock the library routines themselves, at least when checking how your own app will handle the timestamps.

The best approach by far is to build your own date/time service routine(s) which you use exclusively in your application code, and build into that the ability for tests to supply fake results as required. For example, I do a more complex equivalent of this sometimes:

# in file apptime.py (for example)
import time as _time

class MyTimeService(object):
    def __init__(self, get_time=None):
        self.get_time = get_time or _time.time

    def __call__(self):
        return self.get_time()

time = MyTimeService()

Now in my app code I just do import apptime as time; time.time() to get the current time value, whereas in test code I can first do apptime.time = MyTimeService(mock_time_func) in my setUp() code to supply fake time results.

Update: Years later there's an alternative, as noted in Dave Forgac's answer.