Kodeclik Blog

How to add Time Delays to your Python program

In some programming scenarios, it's essential to introduce delays or pauses in your code execution. For instance if you are doing some animation or graphics you might want to introduce delays to make sure characters are orchestrated in the order and sequence you desire. If you need to simulate real-time behavior or control timing for synchronization, you will need to add time delays to your program.
In this blog post, we will explore different approaches to incorporate delays in Python.

Method 1: Use the time.sleep() function

The first approach uses the time module in Python, specifically the sleep() function, which allowing you to pause the execution for a specified number of seconds.
Here's a sample program using time.sleep():
If you run this program, you will see “Starting” printed first:
And then 3 seconds later the second line will be printed so the output looks like:
The time.sleep() function allows you to introduce precise delays and control the timing of your code. This approach essentially suspends execution for the specified number of seconds. The argument can also be a floating point number (i.e., it need not be an integer) to indicate a more precise sleep time.

Method 2: Run your own delay loop using the datetime module

Python's datetime module provides additional capabilities for introducing delays, especially when dealing with shorter durations.
Here's an example of how you can utilize it.
In the above code we first create an interval (using the timedelta function) specifying an interval gap as 3 seconds. Then we print our “Starting” message and record the current time in the “current_time” variable. After this we get into a while loop where we keep re-finding the current time and comparing it to the stored current time (which was the start of the loop). If it is within the specified interval we continue the loop, else we exit the loop. The output is as before (after 3 seconds have passed):
The timedelta() function allows for very granular specification of time. In particular, it takes multiple arguments such as milliseconds, seconds, minutes, hours, days and even weeks! You can specify multiple such arguments to obtain a very granular specification of time. For instance consider the updated program:
This program essentially does a delay of 3 seconds plus 1000 milliseconds = 4 seconds (with the same outputs as before).

Method 3: Use the asyncio.sleep() function

If you are working with asynchronous programming in Python, the asyncio module provides powerful features for introducing delays. Here's an example:
In this snippet, we define an async function sample_delay() that uses the await asyncio.sleep() statement to pause the execution for 3 seconds. By leveraging asyncio, you can incorporate delays while maintaining the responsiveness of your program, especially when dealing with concurrent tasks and asynchronous operations.
The output is the same as before:
Adding delays in Python is a valuable technique for controlling timing, simulating real-time behavior, and synchronizing operations. In this blog post, we have presented three different methods for introducing delays in Python: using time.sleep() for general delays, utilizing datetime for more granular delays, and leveraging asyncio for asynchronous programming scenarios. Understanding these techniques allows you to incorporate delays effectively into your code, enhancing its efficiency and functionality. Which method is your favorite?
If you liked this blogpost, checkout our blogpost on how to end a Python program.
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

Copyright @ Kodeclik 2023. All rights reserved.