How can I make a time delay in Python?

0 votes
asked Feb 4, 2009 by user46646

I would like to know how to put a time delay in a Python script.

8 Answers

0 votes
answered Feb 15, 2008 by pobk

You can use the sleep() function in the time module. It can take a float argument for sub second resolution.

from time import sleep
sleep(0.1) # Time in seconds.
0 votes
answered Feb 4, 2009 by evan-fosmark
import time
time.sleep(5)   # delays for 5 seconds. You can Also Use Float Value.

Here is another example where something is run approximately once a minute:

import time 
while True:
    print("This prints once a minute.")
    time.sleep(60)   # Delay for 1 minute (60 seconds).
0 votes
answered Feb 4, 2009 by tehvan

Please read https://web.archive.org/web/20090207081238/http://faqts.com/knowledge_base/view.phtml/aid/2609/fid/378, which can help you further:

Try the sleep function in the time module.

import time
time.sleep(60)

And put this in a while loop and a statement will only execute on the minute... That allows you to run a statement at predefined intervals regardless of how long the command takes (as long as it takes less than a minute or 5 or 60 or whatever you set it to) For example, I wanted to run a ping once a minute. If I just time.sleep(60) or time.sleep(45) even, the ping will not always take the same amount of time. Here's the code :)

time.sleep(time.localtime(time.time())[5])

The [5] just pulls the seconds out of the time.localtime()'s return value.

The great thing about time.sleep is that it supports floating point numbers!

import time
time.sleep(0.1) 

http://python.org/doc/current/lib/module-time.html

0 votes
answered Feb 14, 2014 by jan-vlcinsky

A bit of fun with sleepy generator.

The question is about time delay. It can be fixed time, but in some cases we might need a delay measured since last time. Here is one possible solutions:

Delay measured since last time (waking up regularly)

The situation can be, we want to do something as regularly as possible and we do not want to bother with all the last_time, next_time stuff all around our code.

buzzer generator

Following code (sleepy.py) defines buzzergen gerenarator

import time
from itertools import count

def buzzergen(period):
    nexttime = time.time() + period
    for i in count():
        now = time.time()
        tosleep = nexttime - now
        if tosleep > 0:
            time.sleep(tosleep)
            nexttime += period
        else:
            nexttime = now + period
        yield i, nexttime

Invoking regular buzzergen

from sleepy import buzzergen
import time
buzzer = buzzergen(3) # planning to wake up each 3 seconds
print time.time()
buzzer.next()
print time.time()
time.sleep(2)
buzzer.next()
print time.time()
time.sleep(5) # sleeping a bit longer than usually
buzzer.next()
print time.time()
buzzer.next()
print time.time()

and running it we see:

1400102636.46
1400102639.46
1400102642.46
1400102647.47
1400102650.47

We can also use it directly in a loop:

import random
for ring in buzzergen(3):
    print "now", time.time()
    print "ring", ring
    time.sleep(random.choice([0, 2, 4, 6]))

and running it we might see:

now 1400102751.46
ring (0, 1400102754.461676)
now 1400102754.46
ring (1, 1400102757.461676)
now 1400102757.46
ring (2, 1400102760.461676)
now 1400102760.46
ring (3, 1400102763.461676)
now 1400102766.47
ring (4, 1400102769.47115)
now 1400102769.47
ring (5, 1400102772.47115)
now 1400102772.47
ring (6, 1400102775.47115)
now 1400102775.47
ring (7, 1400102778.47115)

As we see, this buzzer is not too rigid and allow us to catch up regular sleepy intervals even if we oversleep and get out of regular schedule.

0 votes
answered Sep 15, 2017 by prossellob

To put a time delay you should import the time module. And with that module you only need to write:

time.sleep(The amount of time)

For example if you want to put a time delay of a second before the computer runs another line you should put:

time.sleep(1)
print('Hello World!')

That's all :)

0 votes
answered Sep 15, 2017 by matthew-miles

delays are done with the time library, specifically the time.sleep() function...

To just make it wait for a second:

from time import sleep
sleep(1)

This works because by doing:

from time import sleep

you extract the sleep function only from the time library which means you can just call it with:

sleep(seconds)

rather than having to type out:

time.sleep()

which is awkwardly long to type.

With this method, you wouldn't get access to the other features of the time library and you can't have a variable called sleep. but you could create a variable called time.

Doing from [library] import [function] (, [function2]) is great if you just want certain parts of a module.

You could equally do it as:

import time
time.sleep(1)

and you would have access to the other features of the time library like time.clock() as long as you type time.function but you couldn't create the variable time.

0 votes
answered Sep 15, 2017 by laura-cookson

The tkinter library in the Python standard library is an interactive tool which you can import. Basically, you can create buttons and boxes and popups and stuff that appear as windows which you manipulate with code.

If you use tkinter, DO NOT USE TIME.SLEEP() because it will muck up your program. This happened to me. Instead, use root.after() and replace the values for however many seconds, with a milliseconds. E.g, time.sleep(1) is equivalent to root.after(1000) on tkinter.

Otherwise, time.sleep(), which many answers have pointed out, is the way to go.

0 votes
answered Sep 15, 2017 by aaron-hall

How can I make a time delay in Python?

In a single thread I suggest the sleep function:

>>> from time import sleep

>>> sleep(4)

This actually suspends the processing of the thread in which it is called by the operating system, allowing other threads and processes to execute while it sleeps.

Use it for that purpose, or simply to delay a function from executing. For example:

>>> def party_time():
...     print('hooray!')
... 
>>> sleep(3); party_time()
hooray!

"hooray!" printed 3 seconds after I hit Enter.

Example using sleep with multiple threads and processes

Again, sleep suspends your thread - it uses next to zero processing power.

To demonstrate, create a script like this (I first attempted this in an interactive Python 3.5 shell, but sub-processes can't find the party_later function for some reason):

from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed
from time import sleep, time

def party_later(kind='', n=''):
    sleep(3)
    return kind + n + ' party time!: ' + __name__

def main():
    with ProcessPoolExecutor() as proc_executor:
        with ThreadPoolExecutor() as thread_executor:
            start_time = time()
            proc_future1 = proc_executor.submit(party_later, kind='proc', n='1')
            proc_future2 = proc_executor.submit(party_later, kind='proc', n='2')
            thread_future1 = thread_executor.submit(party_later, kind='thread', n='1')
            thread_future2 = thread_executor.submit(party_later, kind='thread', n='2')
            for f in as_completed([
              proc_future1, proc_future2, thread_future1, thread_future2,]):
                print(f.result())
            end_time = time()
    print('total time to execute four 3-sec functions:', end_time - start_time)

if __name__ == '__main__':
    main()

Example output from this script:

thread1 party time!: __main__
thread2 party time!: __main__
proc1 party time!: __mp_main__
proc2 party time!: __mp_main__
total time to execute four 3-sec functions: 3.4519670009613037

Multithreading

You can trigger a function to be called at a later time in a separate thread with the Timer threading object:

>>> from threading import Timer
>>> t = Timer(3, party_time, args=None, kwargs=None)
>>> t.start()
>>>
>>> hooray!

>>> 

The blank line illustrates that the function printed to my standard out and I had to hit Enter to ensure I was on a prompt.

The upside of this method is that while the Timer thread was waiting, I was able to do other things, in this case, hitting Enter one time - before the function executed (see the first empty prompt).

There isn't a respective object in the multiprocessing library. You can create one, but it probably doesn't exist for a reason. A sub-thread makes a lot more sense for a simple timer than a whole new sub-process.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...