Mastering Python (92 Blogs) Become a Certified Professional
AWS Global Infrastructure

Data Science

Topics Covered
  • Business Analytics with R (26 Blogs)
  • Data Science (20 Blogs)
  • Mastering Python (86 Blogs)
  • Decision Tree Modeling Using R (1 Blogs)
SEE MORE

Python time sleep() – One Stop Solution for time.sleep() Method

Last updated on Nov 27,2024 5.4K Views

Aayushi Johari
A technophile with a passion for unraveling the intricate tapestry of the... A technophile with a passion for unraveling the intricate tapestry of the tech world. I've spent over a decade exploring the fascinating world of...
30 / 62 Blog from Python Fundamentals

At times, we require our program or sections of our program to execute after a small duration. Python makes this task effortless through time.sleep() function. This article covers the functionality of this function along with its applications. 

Before moving on, let’s take a quick look at the topics covered in this article:

    Let’s get started. :)

    Why use Python time.sleep()?

    Sleep function plays a very important role in a situation where we want to halt the program flow and let other executions happen. This function is defined in both versions of python i.e 2 and 3. It belongs to the time module of Python. It basically adds a delay to the execution and it will only pause the current thread and not the whole program. 

    The time Module

    Python time.sleep() function is present in the time module of Python. Before making use of this Python function, you will need to import this module using the command:

    
    import time
    
    

    Once this module is imported, you can make use of time.sleep() function. The syntax is as follows:

    SYNTAX:  

    sleep(seconds)

    It takes one parameter which is seconds as you can see. This basically induces a delay for that many seconds during the execution. Return value for this function is void.

    Let’s now take some examples to understand the working of this function.

    Python time.sleep() Examples:

    Consider the following example that induces a delay of one second between outputs.

    Example:

    import time # import time module
    sleep_time = 1  # time to add delay after first print statement
    print('Hello')
    time.sleep(sleep_time)  # sleep time
    print('Edureka!')
    

    Output:

    If the above code is executed it will add a delay in the program thus, the next statement will be executed after 1 second(s). For an exact delay, you can also pass floating-point values to the function. For example, if 0.1 seconds is passed then it will make a delay of 100 milliseconds.

    Here is another example which will return the system time before and after the execution of the program.

    Example:

    # sleep demonstration
    import time
    # Start time
    print("The time of code execution begin is : ", end ="")
    print(time.ctime())
    # haulting program
    time.sleep(6)
    # end time
    print("The time of code execution end is : ", end ="")
    print(time.ctime())
    

    Output:

    The time of code execution begin is : Sun Jun 23 22:36:19 2019
    The time of code execution end is : Sun Jun 23 22:36:25 2019
    Process returned 0 (0x0)        execution time : 6.089 s
    Press any key to continue . . .

    Sleep Example:

    Following is an example of sleep function:

    import time
    startTime = time.time()
    for i in range(5, 10):
      print(i)
      # making delay for 1 second
      time.sleep(1)
    endTime = time.time()
    elapsedTime = endTime - startTime
    print("Elapsed Time = %s" % elapsedTime)
    

    Output:

    5
    6
    7
    8
    9

    Elapsed Time = 5.006335258483887
    Process returned 0 (0x0)        execution time : 5.147 s

    The complete execution has taken 5 seconds as the execution halted for 1 second(s) each time. Also, the extra time which required for execution is the time of system doing background operations for the programs.

    Different delay time of python sleep()

    Different delay times can be added between the execution of the program in Python depending on the required output. Following code demonstrate how that can be done:

    Example:

    import time
    for i in [1, 0.1, 2, 0.3]:
      print("I will sleep for %s" % i, end='')
      print(" seconds")
      time.sleep(i)
    

    Output:

    I will sleep for 1 seconds
    I will sleep for 0.1 seconds
    I will sleep for 2 seconds
    I will sleep for 0.3 seconds

    Process returned 0 (0x0)        execution time : 3.538 s

    Lazy printing :

    If you want to print something in a fancy way you can do so using the sleep() function as below:

    # importing time module
    import time
    message = "Some fancy character printing!"
    for i in message:
       print(i)
       time.sleep(0.3)
    

    If you execute the above code you will see a delay in the printing of each character which will look fancy.

    Python Thread Sleep

    In multithreaded environment sleep() proves to be very important as while execution it can add a delay in the current thread which is being executed.

    Example:

    import time
    from threading import Thread
    class Runner(Thread):
       def run(self):
           for x in range(0, 7):
               print(x)
               time.sleep(2)
    class Delay(Thread):
       def run(self):
           for x in range(106, 109):
               print(x)
               time.sleep(7)
    print("Staring Runner Thread")
    Runner().start()
    print("Starting Delay Thread")
    Delay().start()
    print("Done")
    

    Below is the output of the threading example above:

    python thread sleep- Python Sleep - EdurekaOutput:

    If you execute the program you will notice that the whole program doesn’t get stopped but, only the thread which was currently being executed, go ahead and give it a try.

    Application :

    There are many applications of this method, for example, we can use it to create a nice user interface which prints menu or the heading in some fancy way, however, one of the important application is to halt a background process which is to be executed in some interval.

    Application Example:

    import time
    string = "Edureka!"
    print_string = ""
    for i in range(0, len(string)):
       print_string = print_string + string[i]
       print(print_string)
       time.sleep(2)
    

    Output:

    E
    Ed
    Edu
    Edur
    Edure
    Edurek
    Edureka
    Edureka!


    As we have seen that the sleep function pauses the program for some amount of time where Python’s time module comes in handy. Let’s see a little about how can we take input from the user and use the same function dynamically.

    Dynamic Sleep Example

    Here’s an example of sleep that takes input from the user to add a delay between two print functions and prints the time taken to execute the print function, the following example is based on Python 3.x.

    import time
    def sleeper():
    	while True:
    		num = input('Enter wait time: ')
    		try:
    			num = float(num)
    		except ValueError:
    			print('Number only.n')
    			continue
    			# Run our time.sleep() command,
    			# and show the before and after time
    		print('Before: %s' % time.ctime())
    		time.sleep(num)
    		print('After: %sn' % time.ctime())
    
    try:
    	sleeper()
    except KeyboardInterrupt:
    	print('nnException Exiting.')
    	exit()
    

    Output:

    Enter wait time: 1
    Before: Sun Jun 23 22:44:13 2019
    After: Sun Jun 23 22:44:14 2019
    Enter wait time: 3
    Before: Sun Jun 23 22:44:16 2019
    After: Sun Jun 23 22:44:19 2019

    Accuracy 

    If you want to stop execution for a smaller period of time there are limitations to this function depending on the operating system as this function uses operating systems sleep() function, in Linux the wait time can be smaller than that compared with windows.

    Summary

    In the above article we covered the sleep() method in python which is basically used to add a delay in program execution, this package is in the time module in Python which basically uses sleep() function of the underlying operating system. We also covered few code examples of how to use this function and took a look into applications of sleep. Demonstrated fancy ways to use this function also how it works in a threaded environment.

    To get in-depth knowledge on Python along with its various applications, you can enroll for live Python online training with 24/7 support and lifetime access.

    Got a question for us? Please mention it in the comments section of this “Python time sleep method in Python” blog and we will get back to you as soon as possible.

    Upcoming Batches For Data Science with Python Certification Course
    Course NameDateDetails
    Data Science with Python Certification Course

    Class Starts on 15th February,2025

    15th February

    SAT&SUN (Weekend Batch)
    View Details
    Comments
    0 Comments

    Join the discussion

    Browse Categories

    webinar REGISTER FOR FREE WEBINAR
    REGISTER NOW
    webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

    Subscribe to our Newsletter, and get personalized recommendations.

    image not found!
    image not found!

    Python time sleep() – One Stop Solution for time.sleep() Method

    edureka.co