How do I make a time delay?

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:
import time

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

Watch a course Python - The Practical Guide

  1. datetime.timedelta(): This function is part of the datetime module in Python and allows you to specify a duration. You can then add this duration to a datetime object to get a new datetime object in the future. For example, to create a delay of 2 seconds, you can use the following code:
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 create a delay. 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 create a delay of 2 seconds:
import time

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

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