Time Module in Python

Learn via video courses
Topics Covered

Overview

Are you looking for an end-to-end guide that can walk you through the core understanding of the time module in python?

Well, worry not we have got you covered. The below module aims at explaining the time module in python from its very basics. The time module in python is an inbuilt module that needs to be imported when dealing with dates and times in python. It explains the use of various time-related functions that are defined in the time module in python along with the multiple code examples to help the users understand the topic better.

Introduction to Time Module in Python

Whenever dealing with time-related tasks, we can always leverage the inbuilt time module in python. It is an inbuilt module that provides various ways in which we can represent the time in code, like numbers, strings, and objects. It has other functions as well, such as waiting until the code executes, functionality such as getting the current time, execution of the program can also be paused, and measuring the efficiency of the code.

We shall be deep-diving into the core concepts of working with dates and times, in addition to representing time using the floats, tuples, and struct_time. We shall also understand suspend thread execution and will learn how to convert different time representations.

The time module in python is a very convenient way of working and using functions and objects with time in python. So, if you want to start incorporating this time module in python, we need to first start by importing the module.

Syntax:

Introduction to time module in python

What is an Epoch?

Till now, we learned how we can leverage the time module in python. Now, we shall be understanding how we can start managing the time with a floating-point number that represents the elapsed time starting from the beginning.

Note that we always consider a period by its starting point when we deal with dates and time in python. And this starting point is what we call the epoch in computing language.

An epoch of time can be defined as the starting point from which we can measure the passage of time.

Let us take an example to understand the meaning of epoch better. If we calculate the epoch, then midnight of March 1, 2010, will be defined as the epoch, then we will be able to represent the midnight of March 2, 2010, UTC as 86400 seconds since the epoch. This is calculated as 24 hours a day, we have 24 hours. Each hour is 60 minutes long and each minute consists of 60 seconds. So technically, 2 Mar 2010 UTC will be the only day after the epoch.

Applying the basic math

60 * 60 * 24 = 86400

Interestingly, we can define time before the epoch as well. It will be negative as we consider the time after the epoch as positive. Undertaking the same situation, if we consider midnight of 31 March 2010 as -86400 seconds, considering an epoch to be midnight of 1 March 2010. While January 1, 1970, UTC is a common epoch, it is not the only epoch used in computing. Different operating systems, filesystems, and APIs sometimes use different epochs.

unix epoch

Summing up, the epoch can be defined as the point where the time starts and is platform-dependent. The epoch is 1 January 1970, 00:00:00 (UTC) where leap seconds are not calculated for the time in seconds since the beginning of the epoch in many Windows and Unix systems. For the Win32 API, the epoch is defined as January 1, 1601.

Important Functions in the Time Module

Listed below are the various important functions in the time module in python, along with examples that can help you understand the topic a little better.

Python time.time()

Definition:

The time.time() function in the time module in python can be defined as the number of seconds that have passed since the epoch or the current time passed since the epoch in seconds. Usually, it is represented in floating-point numbers.

The point when the time begins is defined as the epoch for the Unix system as January 1, 1970, 00:00:00 at UTC.

Syntax:

Code:

Output:

Explanation:

Here we started by importing the time module in python. Then we have defined the variable time_seconds as time.time() function which when called results in the current time since the beginning of the epoch.

Python time.ctime()

Definition:

The time.ctime() function in the time module in python is calculated as the number of seconds that passed since the epoch as a variable argument. Then, it returns a time string that represents the local current time in 24 characters or mentioned milliseconds.

If we don't pass any number of seconds in the variable argument, then it computed times till the present.

Syntax:

Code:

Output:

Explanation:

Here we started by importing the time module in python. Then we have passed the seconds value in the 'sec' variable, which we have used while implementing the time.ctime() function in python. Hence, we obtain the time by taking the 'sec' value as the epoch and the current local time is generated.

Python time.sleep()

Definition:

The time.sleep() function in the time module in python is implemented, when we want to call for suspension or delay in the execution of the current thread for the mentioned number of seconds. It is widely used to halt the program or delay the execution for the specified time that has been set in the argument.

Syntax:

Code:

Output:

Explanation:

Here, we started by importing the time module in python. We define the seconds until which we need to halt the program to print the next line as 10 in the case mentioned above. So, eventually we initially get the first statement printed but it took 10 seconds to print the second statement.

time.struct_time Class

Definition:

The struct_time class in the time module in python is described as the class that helps out to access the local time, majorly the non-epochal timestamps. The output obtained is usually a named tuple whose value is obtained by both attribute name and index.

The various attributes that are associated with the struct_time object are as follow:

IndexAttribute NameValues
0tm_year0000, …, 9999
1tm_mon1, 2, …, 11, 12
2tm_mday1, 2, …, 30, 31
3tm_hour0, 1, …, 22, 23
4tm_min0, 1, …, 58, 59
5tm_sec0, 1, …, 60, 61
6tm_wday0, 1, …, 6; Sunday is 6
7tm_yday1, 2, …, 365, 366
8tm_isdst0, 1 or -1

This class has many functions, let us dive deep into each one of them.

time.localtime()

Definition:

The time.localtime() function in the time module in python can be defined as a function that first takes epoch as the number of seconds that have passed in an argument. It then results in the struct_time object given by local time.

It must be noted that if the argument states the number of seconds that have passed since the epoch, then it shall result in the current time returned by the time.time() function.

Syntax:

Code:

Output:

Explanation:

Here, we started by importing the time module in python. Then we have passed the seconds value in the 'sec' variable, which we have used while implementing the time.local time() function in python. Hence, we obtain the time by taking the 'sec' value as the epoch, and the struct_time is generated as observed.

time.mktime()

Definition:

The time.mktime() function in the time module in python can be defined as the inverse operation of the time.localtime() function. This time.mktime() function first takes the struct_time or a tuple that contains 9 elements concerning the 'struct_time' as a dynamic argument. It then outputs the local time as the seconds passed since the epoch. This can be said to be the exact opposite or inverse of the time.localtime() function.

Syntax:

Code:

Output:

Explanation:

Here we started by importing the time module in python. Then, we gave a value to the variable sec. Now when we used the value of the variable in the time.localtime(sec) function, we get the output as the struct_time local time. As we studied, the time.mktime() function is the inverse operation of the time.localtime() function. Hence, we get the output as the seconds that passed since the beginning of the epoch.

time.asctime()

Definition:

The time.asctime() function in the time module in python can be defined as the function that can convert a tuple that contains 9 elements concerning the strcut_time or the time.struct_time object where the time is obtained by time.gmtime() or time.localtime() method. This struct_time represents the time in the following given format.

Day Mon Date Hour:Min: Sec Year

Syntax:

Code:

Output:

Explanation:

Here we started by importing the time module in python. Then we obtain the struct_time using the time.localtime() function. Once the output is obtained, we make use of the asctime() function to obtain the string in the format as defined in the asctime() definition.

time.gmtime()

Definition:

The time.gmtime() function in the time module in python can be defined as the struct_time in the UTC timezone after taking the number of seconds passed since the beginning of the epoch as a variable argument. While understanding the time.gmtime() function, we first convert the time ( expressed in seconds since the beginning of the epoch) to a time.struct_time object in UTC. Here the 'tm_isdst' attribute always remains 0.

But if sometimes the second parameter is kept blank or not entered, then-current the local time is returned as per time.time() function.

Syntax:

Code:

Output:

Explanation:

Here we started by importing the time module in python. Then we give value to the variable 'sec'. We then use this variable in the time.gmtime() function to obtain the strcut_time in UTC.

time.strftime()

Definition:

The strftime() function in the time module in python can be defined as the struct_time or tuple that corresponds to it as a dynamic argument. Now it outputs the strings representing the same which is entirely based on the format code or argument that was specified.

But when it is not specified, the current local time is returned as the time.localtime() function used where the format needs to be a string. We might also get errors like ValueError when any field is out of the range allowed.

Syntax:

Code:

Output:

Explanation:

Here we started by importing the time module in python. Then we extracted the struct_time using the time.localtime()function. We could have used the time.gmtime() function for the same. Then, after the local time is obtained, we use the time.sftime() function to extract the time as per the format code specified.

time.strptime()

Definition:

The strptime() function in the time module in python can be defined as the struct_time object that is obtained after parsing the string which represents the time.

Syntax:

Code:

Output:

Explanation:

Here we started by importing the time module in python. Then, we parse this string value into the time.strptime() function to obtain the struct_time as observed.

Using the Time Module

Below are two examples that will help us to understand, how we can calculate the time that the code took for execution and make use of the time module to efficiently use the time module in python.

Example 1: Calculate the time for code execution

Now let us deep-dive into an example where we shall be using the time module to calculate the time it takes to execute a piece of code.

Code:

Output:

Explanation:

Here we started by importing the time module in python. Then we calculate two values of time, where one value is when we are starting the code execution and the other is when the code execution is at the end. We have used the time.time() in the first_value as well as the second_value to get the time of the execution. Then we printed the final result by subtracting the second value from the first, and hence we were able to calculate the time in which the code got executed.

Example 2: Calculate the time for code execution using the sleep method

Now let us deep-dive into an example where we shall be using the sleep method of the time module in python to delay the execution of code.

Code:

Output:

Explanation:

Here we started by importing the time module in python. Then two values of time are calculated, where one value is when we are starting the code execution, and the other is when we implement the sleep method to halt the execution of code by 4 seconds in the end.

Then we printed the final result by subtracting the second value from the first, and hence we were able to calculate the time in which the code got executed. The code stops executing for n number of seconds passed as a parameter to time.sleep().

All Functions in the Time Module

Summing up all the functions in the time module with their brief definition

Time FunctionsDefinition
time.time()Defined as the time elapsed in seconds since the beginning of epoch which for UNIX system is calculated from 1 Jan 1970.
time.ctime()Defined as the time where we pass seconds since epoch in a variable argument and returns a time string that represents the local current time.
time.asctime()calculates the current time in hour:minutes format
time.gmtime()Defined as the time where we first enter the seconds since epoch and get the struct_time in UTC.
time.sleep(n)Defined as the number of seconds that can be passed in the argument until which we want the program to halt or delay.
time.localtime()Defined as the time where we pass seconds since epoch in a variable argument and return a time string that represents struct_time in local time
time.mktime()Considered as inverse operation of time.localtime() where it outputs the local time as the seconds passed since the epoch.
time.gmtime()Defined as struct_time in UTC timezone after taking the number of seconds passed since the beginning of the epoch as a variable argument
time.strftime()Defined as taking the struct_time as a variable argument that returns the time string based on the format code specified.
time.strptime()Defined as the struct_time object that is obtained after parsing the string which represents the time.

Conclusion

  • The time module in python is an inbuilt module that provides various ways in which we can represent the time in code, like numbers, strings, and objects. It has other functions as well such as waiting until the code executes, functionality such as getting the current time, execution of the program can also be paused, and measuring the efficiency of the code.

  • The epoch can be defined as the point when the time starts and is platform-dependent. The epoch is 1 January 1970,00:00:00 (UTC) where leap seconds are not calculated for the time in seconds since the beginning of the epoch in many Windows and UNIX systems.

  • All the important time function in the time module of python has been summarized above under the heading "All functions in the time module" to help you revise every function altogether.

  • Covered the example where we learned how we can make use of time.time() function and time.sleep() function to calculate the time taken by the code to get executed.

Read More: