×

Python Time Module

Python contains many files that can be imported into a python code and used whenever we want. One of that modules is the time module. It is a good practice to know about the modules in python.

Python time module allows the programmer to work with time in python. It gives us a lot of functionality, like working with the current time, getting the current time, pausing the code from execution, etc.

How can we use the Python time module?

This is a standard utility module in python. We don’t have to download it. To start working with this module, we first have to import it. We can do that using the following syntax.

import time

What is epoch?

An epoch is like a starting point from where the time starts, and it is platform-dependent. The point where the time starts is called an epoch. We use time.gmtime(0) to check the epoch on a particular platform.

Let’s see the example of getting an epoch:

import time
 
print(time.gmtime(0))

Python time module contains a good amount of functions with different functionality like:

  • time.time()
  • time.ctime()
  • time.sleep()
  • time.gmtime()
  • time.mktime()
  • time.localtime()
  • time.strptime()
  • time.strftime()
  • time.asctime()

time.time() method

This method is used to give the current seconds since the epoch. It will give the seconds of the current local time.

Syntax

time.time()

Example:

import time
sec = time.time()
print("Current time in seconds since epoch =", sec) 

Output

Current time in seconds since epoch = 1658772084.8247688

Explanation

In the above code, we have imported the time module using the import statement. After that, we used the time.time() method to get the seconds and stored them in the variable sec.

time.sleep() method

This method in the python time module is used to give the time lapse between the execution of two processes or commands.

Syntax

time.sleep(value)

Example:

import time
print("Tutorial")
time.sleep(1.2)
print("And")
time.sleep(3.2)
print("Examples")

Output

Tutorial
And
Examples
time.localtime()

Explanation

In the above code, we have imported the time module using the import statement. After that, we used the time.sleep() method between two consecutive executions to give the time lapse between them.

time.localtime() method

This method in the python time module is used to access many local time-stamp fields like seconds, hours, years, etc.

Let’s understand this with an example:

  • tm_hour: It is used to get the hour of that local time.
  • tm_min: It is used to get the minutes of the local time.
  • tm_sec: It is used to get the second of the local time.
  • tm_year: It is used to get the particular year of the local time.
  • tm_mon: It is used to give the month of the particular local time.
  • tm_mday: It used to give the date of the month of the local time.
  • tm_wday: It is used to give the week of the month.
  • tm_yday: It is used to give the number of days ranging from 1-366.

Syntax

time.localtime(seconds)

Example

import time
 
lt = time.localtime()
print("Time:",lt)
print("Current year is:", lt.tm_year)
print("Current hour is:", lt.tm_hour)
print("Current minute is:", lt.tm_min)
print("Current second is:", lt.tm_sec)

Output

Time: time.struct_time(tm_year=2022, tm_mon=7, tm_mday=25, tm_hour=18, tm_min=20, tm_sec=47, tm_wday=0, tm_yday=206, tm_isdst=0)
Current year is: 2022
Current hour is: 18
Current minute is: 20
Current second is: 47

Explanation

In the above code, we have imported the time module using the import statement. After that, we used the variable to store the value returned by the time.localtime() method. After that, using that variable method we printed the values.

time.ctime()

It returns a string value of the current local time.

Syntax

ctime(seconds)

Example

from time import time
from time import ctime
 
ct = time()
x = ctime(ct)
print("Local_time:",x)

Output

Local_time: Mon Jul 25 18:24:21 2022

Explanation

In the above code, we have imported the time and ctime module using the import statement. After that, we used the variable to store the value returned by the time() and ctime() methods. Then we printed it.

time.mktime()

This method of the python time module is the reverse of the localtime method. In this method, we give the time in standard local time and it returns it in seconds.

Syntax

time.mktime()

Example

import time
 
lt = time.localtime()
s = time.mktime(lt)
print(s)

Output

1658773576.0

Explanation

In the above code, we have imported the time module using the import statement. After that, we used a variable to store the value returned by the time.localtime() method and then we passed that variable as an argument to the time.mktime() method.

time.gmtime()

It simply returns the current time details.

Syntax

time.gmtime()

Example

import time


lt = time.gmtime()
print(lt)

Output

time.struct_time(tm_year=2022, tm_mon=7, tm_mday=25, tm_hour=18, tm_min=28, tm_sec=50, tm_wday=0, tm_yday=206, tm_isdst=0)

Explanation

In the above code, we have imported the time module using the import statement. After that, we used a variable to store the value returned by the time.gmtime() method, and then we printed that variable.

time.strptime()

This method of the python time module accepts a string representation of the current time and returns the details of the time.

Syntax

time.strptime(string, %format code)

Example

import time
 
tm = "26 July, 2022"
s = time.strptime(tm, "%d %B, %Y")
print(s)

Output

time.struct_time(tm_year=2022, tm_mon=7, tm_mday=26, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=207, tm_isdst=-1)

Explanation

In the above code, we have imported the time module using the import statement. After that, we used a variable to store the time value in the standard format, and then we used another variable for the value returned by the time.strptime() method, and then we printed that variable.

time.strftime()

This method of the python time module is used to take the tuple of struct_time and returns the time in details.

Syntax

time.strftime(%format code, struct_time)

Example

import time
 
tm = time.localtime()
x = time.strftime("%d/%m/%Y, %H:%M:%S",tm)
 
print(x)

Output

25/07/2022, 18:32:12

Explanation

In the above code, we have imported the time module using the import statement. After that, we used a variable to store the value returned by the time.localtime() method, and then we used another variable that will store the value returned by the time.strftime() method. Then we print the value.

time.asctime()

Syntax

time.asctime()

Example

import time
 
tm = time.localtime()
 
o = time.asctime(tm)
print("TimeStamp:",o)

Output

TimeStamp: Mon Jul 25 18:33:59 2022

Explanation

In the above code, we have imported the time module using the import statement. After that, we used a variable to store the value returned by the time.localtime() method, and then we used a variable to store the value returned by the time.asctime() method .

Delaying Execution of programs:

For delaying the execution, we can use time.sleep() method.  This method can be used for halting the program execution in the time-specified arguments.

Let’s take an example: Delaying of execution time in Python programs.

Example

import time
for x in range(5) :
#using sleep() to halt execution
time.sleep(1)
print(x)  

Output:

0
1
2
3
4

Explanation

In the above code, we have imported the time module using the import statement. After that, we used for loop to iterate it through a given range. After that, the value will be printed each time the loop will iterate with a certain time lapse. In this case, the time lapse is 1sec.

Python Time in Seconds as floating point number

time.time(): Firstly, it returns the number of seconds which already passed since the epoch. To account for fractional seconds, the return value is a floating point number.

Python

>>>  from time import time
>>>  time()
1551243539. 932719

The number may differ on your machine or may be very different due to the reference point, which is considered to be the epoch that may be very different.


Related Topics

Best Python AI Projects

Artificial consciousness is advancing quickly, from Chabot's to self-driving vehicles. Because of the various advantages and development presented by AI, numerous enterprises have begun searching for AI-fueled applications. Thus, there...

7 minutes read.

Self in Python

 “self" is neither a keyword nor has a special meaning in Python, but it has a place and a job to do in Object-oriented programming. When we create a class...

6 minutes read.

Not supported between instances of str and int in python

In this article, you are going to learn why the type error occurs between instances of string and integer datatypes. Also, you will know what kind of error is the...

6 minutes read.

Python bool()

Python bool() class The bool() class in Python returns the boolean value for the specified object. Syntax class bool([x]) Parameter object: This parameter represents the object, like String, List, Number etc. Return It will always return True, except...

1 minute read.

Gethostbyname() function in Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

Python Infinity

Introduction We will discover how to define an infinite number in Python in this tutorial. Infinity, as we all know, is a value that cannot be defined and can either be...

5 minutes read.

Removing the First Character from the String in Python

String The string is the collection of characters. The strings in python are “immutable”; we cannot change a string once they are created. In python, whatever data we take as input...

4 minutes read.

Python Assert

Python Assert Python provides an assert statement which is used to check the logical expression. If the given logical expression is true, then it precedes for the next line; otherwise, it raises an...

2 minutes read.

Python globals() function

Python globals() function The globals() function in Python returns the value of the named attribute of object where the ‘name’ must be a string. Syntax globals() Parameter NA Return This function returns the global symbol table as a dictionary. Example...

1 minute read.

Python Multiprocessing Processor

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

4 minutes read.

Creating Tables using Python MySQL

In this article, we are going to learn how to create tables in databases using Python MySQL. Introduction to Tables: Generally, databases are used in order to store the information in the...

9 minutes read.

Difference between Perl and Python

Control and presently utilized for a great many undertakings, including framework organization, web improvement, network programming, and GUI improvement, and the sky is the limit from there. About Perl? Perl is a...

4 minutes read.

Python setattr() function

Python setattr() function The setattr() function sets the value of the specified attribute of the specified object. Syntax setattr(object, name, value) Parameter object: This parameter represents any object. name: This parameter represents the name of the attribute you...

1 minute read.

Python bin() function

Python bin() function The bin() function in Python returns the binary version for the specified integer. Syntax bin(x) Parameter n: This parameter represents an integer or int value. Return This function returns a binary string for the specified integer...

1 minute read.

Write Text files in Python

Let's discuss writing the text file in detail. Generally, writing text also follows the same procedure as like reading text. It varies only in some specific places. Steps followed for writing...

4 minutes read.

Compound Interest GUI Calculator using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

6 minutes read.

Yield Statement In Python

The generators are defined by using the yield statement in Python. Generally, it converts a normal Python function into a generator.  The yield statement hauls the function and returns back the...

2 minutes read.

Python Printf Style Formating

String objects have one special implicit activity: the % administrator (modulo). This is otherwise called the string designing or interjection administrator. Given design % values (where configuration is a string),...

3 minutes read.

Difference between Expression and Statement in Python

What is an expression in Python? Expression is a combination of operands and operators. Expression helps us to produce some other values. In the python programming language,  expressions produce some other value...

6 minutes read.

Difference between Python 2 and Python 3

In this tutorial, we will learn the differences between two versions of python, that is, python version 2 and python version 3. Some basic differences include- Python 2 is the older version...

3 minutes read.