DEV Community

Cover image for time.sleep in Python
bluepaperbirds
bluepaperbirds

Posted on

1

time.sleep in Python

Python has a module to deal with time. This lets you pause/wait some time in your code. To do this, first import the time module

#!/usr/bin/python3
import time

Then you can use the method sleep().

Pause in Python

To sleep or wait, you can use time.sleep()

time.sleep(secs)

To sleep for five seconds

time.sleep(5)

You can also use this to sleep milliseconds

time.sleep(.500)

Thus, the parameter seconds can be either an integer or floating point number.

Pause vs threading

To be clear, it pauses the whole program: "Suspend execution of the calling thread". That means that while it is in the sleep method, it does absolutely nothing, not even listen to keyboard or mouse input.

If you want to do several things at once, look into threading. Every task runs in a thread, so the program could be pausing while still getting keyboard input or receiving to network data.

threading

How accurate is time.sleep() ?

The sleep method in the Python time module uses the operating systems sleep() function. In other words, the systems sleep code.

Because operating systems are not accurate like an atomic clock, they have some delay. But don't worry, this delay is usually 1-10 milliseconds and does not matter for 99% of the apps.

Related links:

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →