W3docs

How do I make a time delay?

There are several ways to add a delay to your Python program.

There are several ways to add a delay to your Python program. Here are three options you can use:

  1. time.sleep(): This function is part of the time module in Python and allows you to specify the amount of time (in seconds) that your program should pause. For example, to pause your program for 2 seconds, you can use the following code:

Making a time delay using time.sleep method in Python

import time

beginning_time = time.time()
print('start')
time.sleep(2)
print('end')
print('time spent:', time.time() - beginning_time)

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

  1. datetime.timedelta(): This class is part of the datetime module and is used to calculate future timestamps, not to pause program execution. You can add a duration to a datetime object to get a new datetime object in the future. For example, to calculate a time 2 seconds from now, you can use the following code:

Add a specific duration to a datetime object in Python

import datetime

delay = datetime.timedelta(seconds=2)
future = datetime.datetime.now() + delay

print(future)
  1. A while loop: You can also use a while loop to wait until a certain amount of time has passed. For example, you can use the current time to calculate how much time has passed, and then use this to determine how much longer you need to wait. Here's an example of how you could use a while loop to wait for 2 seconds:

Making a delay, using a while loop in Python

import time

start = time.time()
while time.time() - start < 2:
    # Do nothing
    pass
print('time spent:', time.time() - start)

Note: This approach uses busy-waiting, which continuously consumes CPU resources. For production code, prefer time.sleep() or asyncio.sleep() instead.

I hope this helps! Let me know if you have any questions.