Time module in python

by Alex
Time module in python

The time module from the standard Python programming language library contains a lot of useful methods for working with time. With it you can get information about the current date and time with millisecond accuracy, display this information in the format you need, as well as control the progress of program execution by adding timer delays.

Current Time in Python

Methods from the time module work based on the common system of time description which is true for Unix as well as POSIX-compatible operating systems. According to its concept, the current time is represented as a plain real value in seconds from the beginning of the epoch to the present day. The starting point for time is January 1, 1970, when the seconds counter had a completely zero value. Since then, this number has grown steadily, allowing people to work with different types of dates in the most accurate representation possible. If necessary, seconds are converted to hours, days, months and years, giving the user a convenient view of the time display. To see the number of seconds that have elapsed since the epoch began, simply call the time() method. But before that, you need to connect the time module using the import operation.

import time


As you can see from the example, the function print takes the number returned from the method time() as the only parameter, and then prints it on the screen. Thus, more than a billion and a half seconds have already passed since January 1, 1970. But this representation of time is quite inconvenient for the user of the program. To display the current date in a more comfortable form, you should pass the result of the ctime() method to the print function, remembering to import the appropriate time library.

import time

Tue Oct 23 10:18:23 2018

The result of executing the above program will display accurate information about the current time, which includes the day of the week, month name, its number, hours, minutes, seconds, and year. In addition, any value in seconds, obtained with the previously mentioned time() method, can be passed as a parameter to the ctime() method.


The standard Python library has many different methods for working with time. The most popular functions implemented in the time module are described in the following table. Here you can find their names as well as a short description.

Method Characteristic
time() returns the current time elapsed since the beginning of 1970 in seconds
ctime(s) returns the local time in string or the time obtained from s seconds
clock() returns the processor time since the first call of this function, the accuracy is greater than 1 microsecond
sleep(s) stops execution of the program for exactly s seconds
strftime(s) converts the time s, passed as an argument, into a string using the format
strptime(s) parses the string s and converts it into a time object in the format
mktime(s) converts time s to the number of seconds since the beginning of 1970
localtime(s) returns an object representing the local time or time s

Formatted Output

The principle of the ctime() method is to present the second real value in a more convenient way, through automatic formatting. For some users, this way of presenting data may seem too complex for perception or insufficiently informative. That’s why methods of the time module allow you to create your own unique formatting types for dates. In this case we will talk about strftime function which takes as parameters the current time and the template which will be used to format the obtained object. The following example demonstrates the output of the value passed by the localtime() function to strftime. That is, we will get the current time in Python and output it in a formatted way. The first argument of the strftime method is a string with some set of rules for formatting, each of which is specified using the % symbol. The result will be an output including the name of the month, the date and the year.

import time
print(time.strftime("Today is %B %d, %Y.", time.localtime()))

Today is October 23, 2018.

There are a large number of formatting characters that are responsible for displaying the individual properties of the object that represents the date. It is important to remember that each new rule must be separated by a % sign. All available format types for outputting time data are described in detail in the following table. You can pass them to the strftime method in any order by putting them in a string literal, which serves as a parameter.

Format Property
%a short name for the day of the week
%A full name of the day of the week
%b short name of the month
%B full name of the month
%c date and time
%d day of the month
%H number of hours in 24-hour format
%I number of hours in 12-hour format
%j day of the year
%m month number
%M number of minutes
%p before or after noon for the 12-hour format
%S number of seconds
%U number of the week of the year, starting on Sunday
%w day of the week
%W number of week of the year, starting from Monday
%x date
%X time
%y year with no indication of century
%Y full presentation of the year
%Z time zone name
%% percent symbol

Using the sleep method

The execution of many tasks in programming involves the passage of time in one way or another. Sometimes a program must stop executing for a set number of seconds, minutes or hours. This may well be necessary when the computer is communicating with some external system, such as a database, which must complete its own tasks before moving on to the next action. You can put a program on hold by temporarily freezing its work using the sleep method available in the time module. Its only argument is the number of seconds the program should wait before proceeding to the next step of the prescribed algorithm. In the following code snippet, the sleep function works for 10 seconds.

import time
pause = 10
print("Program started...")
print(str(pause) + " seconds passed.")

Program started...
10 seconds passed.

As you can see from the results of the code, first the start message is displayed, then the program stops working for exactly 10 seconds, because the sleep method takes the pause variable as its argument. Then the last entry is displayed, informing the user how many seconds the delay lasted.

Often we need to make the delay in milliseconds. Note that the sleep function parameter does not have to be an integer.

Thus, to make a delay of 100 milliseconds we need to write time.sleep(0.1).

Program runtime

There are many different tasks, to solve which you need to find the time spent on the program or its individual blocks. To find this value, just calculate the difference in seconds between the start point of a certain function and the place where it terminates. The following example demonstrates the use of time() methods to get the current time in order to eventually find out how long a code block has been running. The sleep() method here increases the program runtime by 5 seconds.

import time
start = time.time()
finish = time.time()
result = finish - start
print("Program time: " + str(result) + " seconds.")

Program time: 5.00509023663818 seconds.

Despite the simplicity of the above approach, it is not recommended to use it for serious purposes, where accurate and OS-independent results are required. The point is that the numerical value of time, obtained in this way, may have errors due to the internal peculiarities of the computer, in which the program is running. For example, the system clock can be manually adjusted by the user during the execution of the program. The correction can also occur automatically if the system clock is set to be synchronized by NTP. Thus it may happen that the function returns a lower value than the previous call.


For this reason, it is best to use the monotonic() method, which first appeared in Python 3.3 on some platforms and since 3.5 has been available absolutely everywhere. Its main feature is an accurate representation of the amount of time being measured, regardless of the operating system and current platform. The timer used will never return a value which is smaller than the previous one when calling the method again. This avoids many errors as well as unexpected behavior.

import time
start = time.monotonic()
result = time.monotonic() - start
print("Program time: {:>.3f}".format(result) + " seconds.")

Program time: 15.012 seconds.

The example program described above demonstrates the operation of the monotonic() function. Its principle is the same as in the previous example, but here the result has a guaranteed accuracy and is independent of external conditions. Slight formatting of the result is used in order to display the time in a more comfortable form.


Using the standard time library module in Python 3, it is possible to interact with information about the current time in every way. Thus, using the library makes it possible to:

  • Interrupt program execution for the specified number of seconds.
  • Display information about the time elapsed since the beginning of the epoch.
  • Convert the system time value to a convenient form.
  • Measure the execution time of the program as a whole or of its individual modules.

Related Posts