Skip to main content
HomeTutorialsPython

Python time.sleep() Function

In this tutorial, you will learn how the time.sleep() function operates and how to apply it in your program.
Jan 31, 2019  · 7 min read

In this tutorial, you will learn about the Python function sleep() that allows you to introduce a delay in the execution of your program. This is a handy function especially when your program is working with threads or even when you are working with graphics and animations. The sleep function is available within the time module that contains many other functions that deal with time access and conversions. And although this module is available on all platforms, not all functions within it might be available or even work the same exact way. Let's check out the time.sleep() module in more detail...

Time Module

This module provides functions that help manipulate time and use them in your program. There are other "cousin" modules that work more precisely with date and the calendar within your system, but this module is more focused on just manipulating time - working with hours going all the way down to milliseconds.

Some of the terms you will generally hear when working with time in the computer science world is epoch.

But first, make sure you import the time module. To do so simply type:

import time

epoch

This is the precise point when time really started. This doesn't mean the birth of our solar system or when man actually started measuring time, but it is actually relatively closer to now. For the UNIX system, the epoch is January 1, 1970, 00:00:00 (UTC) (It was a Thursday in case you were wondering...) To find out the epoch on your system you can type:

time.gmtime(0)
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)

This will tell you the year (tm_year), month (tm_mon), day (tm_mday), hour (tm_hour), minute (tm_min) and the second (tm_sec). Along with week of the day (tm_wday) - this is 3 since Monday is marked as the beginning of the week and is counted as 0. Then it is followed by the day of the year (tm_yday) aka julian day. And finally, the daylight saving flag (tm_isdst) - DST stands for daylight saving time. This field has values either 0, -1 or 1. 0, if the daylight savings is not in effect. 1, if the daylight savings is in effect and finally -1, if the information is not available. Why not available you ask? Because DST rules are determined by local law and can change.

Most computers store the time and date as a difference of seconds from the date January 1, 1970, 00:00:00 (UTC) and the time that is to be stored. So, if you go ahead and type:

time.time()
1548611182.872067

This will tell you the seconds that have passed since January 1, 1970, 00:00:00 (UTC). This difference is what we call timestamp or UNIX epoch time, and it is in the form of a floating point number. Well... to be honest, the difference is not in terms of seconds but something called ticks. In most UNIX systems, the clock "ticks" 50 to 100 times in a second. So, the UNIX epoch time is actually the number of ticks that have occurred since Jan 1, 1970, 00:00:00 UTC.

So, now that you have an idea about what the time module does. Let's have a look at the sleep() function.

time.sleep()

Simply put, the time.sleep() takes as arguments the number of seconds you want the program to halt or to be suspended before it moves forward to the next step. Let's see this with the help of a simple program, where we simply output the current time with a halt of 5 seconds in between the next execution - hence introducing a difference of 5 seconds between each print of the current time. Using time.ctime() helps to see the local time in a nicely formatted version.

for count in range(5):
    print(time.ctime())
    # Prints the current time with a five second difference
    time.sleep(5)
Sun Jan 27 18:46:24 2019
Sun Jan 27 18:46:29 2019
Sun Jan 27 18:46:34 2019
Sun Jan 27 18:46:39 2019
Sun Jan 27 18:46:44 2019

The syntax for the function is: time.sleep(sec) where sec is the argument that specifies the number of seconds the program is to be suspended for. The function does not return any value.

sec - The argument is actually a floating point number, hence you can make the sleep time more precise. However, this is a little doubtful cause the actual suspension time may be less than that requested time or arbitrarily longer. To understand why better, imagine the program being a problem or a task being handled by a different salesperson in a shop - when you suspend the program the person working on it is assigned another client immediately. But soon after (sooner than the specified sleep secs), another free salesperson takes up the task and goes on to complete it - hence the suspension time can be less. Similarly, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of tasks for all salesperson in the shop, and hence the program has to wait for its turn. Internally, this is more complex of course, and many ways of handling this have been introduced already.

for count in range(3):
    print(time.ctime())
    # Prints the current time with a five second difference
    time.sleep(2.5)
Sun Jan 27 18:46:49 2019
Sun Jan 27 18:46:52 2019
Sun Jan 27 18:46:54 2019

Python makes no guarantees about the behavior of this function calls, especially cross-platform. The underlying reason is that most of the functions defined in this module call platform C library functions with the same name. The accuracy really depends on the underlying operating system's sleep accuracy and if you need to look up further - it will do you good to look at the platform documentation because the semantics of these functions vary among platforms.

However, there is some good news: starting with Python version 3.5, the time.sleep(secs) now sleeps at least secs(argument passed) even if the sleep is interrupted by a signal (again, imagine the signal to be a salesperson as discussed above), except if the signal handler raises an exception.

So, what happens internally when using time.sleep()?
This part is meant for understanding the function even better but is not required for you to start using the function itself. The function actually uses the System Clock, an electronic device in a computer that issues a steady high-frequency signal that synchronizes all the internal components and is part of the processor. This module raises what is called an Interrupt Requests (IRQs) at programmable intervals. The IRQs are responsible for interrupting the current code the processor is executing, saving the current state before passing control to another piece of code in the operating system.
So, what the sleep() function does is that it calls underlying I/O completion routine or asynchronous procedure call to block the process. The OS will note that you don't want to do anything else till a timeout period is reached. So once, this timeout period is reached the OS will resume your process from the last state it remembers. And from your point of view a simple call to the time.sleep() function was made.

Congrats on mastering the time.sleep() function. Be sure to check out DataCamp's Python Data Science Toolbox (Part 1) course to learn more about functions in Python.

Topics

Learn more about Python

Course

Introduction to Python

4 hr
5.5M
Master the basics of data analysis with Python in just four hours. This online course will introduce the Python interface and explore popular packages.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

tutorial

Python While Loops Tutorial

Learn how while loop works in Python.
DataCamp Team's photo

DataCamp Team

4 min

tutorial

Python Print() Function

Learn how you can leverage the capability of a simple Python Print function in various ways with the help of examples.
Aditya Sharma's photo

Aditya Sharma

10 min

tutorial

Python Functions Tutorial

A tutorial on functions in Python that covers how to write functions, how to call them, and more!
Karlijn Willems's photo

Karlijn Willems

14 min

tutorial

Python List Index() Tutorial

In this tutorial, you will learn exclusively about the index() function.
Sejal Jaiswal's photo

Sejal Jaiswal

6 min

tutorial

Python Count Tutorial

Learn how to use the counter tool with an interactive example.
DataCamp Team's photo

DataCamp Team

3 min

tutorial

Definitive Guide: Threading in Python Tutorial

Learn the basic concepts of threading and how you can use it with the help of Python.
Aditya Sharma's photo

Aditya Sharma

12 min

See MoreSee More