×

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

Python locals() function

Python locals() function The locals() function in Python updates and returns a dictionary representing the current local symbol table. Syntax locals() Parameter NA Return This function returns the local symbol table as a dictionary or returns free...

1 minute read.

Python Tkinter Tutorial

What is Tkinter? Tkinter is GUI library of Python. When we integrated Tinkter with Python, it provides an easy and quick way to develop GUI applications. It provides the Tk GUI...

14 minutes read.

Explain sklearn clustering in Python

Make a connection and patterns across datasets by using clustering, one of the unsupervised machine learning approaches. Grouping is crucial because it ensures unlabelled data's natural clustering. The sample from...

7 minutes read.

Python Fit Transform

In machine learning, fit (), transform(), fit transform () methods are provided by scikit learn package. This package is used in model fitting and data processing. These methods are implemented...

2 minutes read.

How to Iterate through a Dictionary in Python

In this tutorial, we will learn how to interate throught the dictionary in the Python programming, using different approaches with example. Introduction to Dictionary in Python Dictionary is a special type of...

4 minutes read.

Python Continue Statement

In Python, loops automate and repeat processes in a cost-effective manner. However, there may be occasions when you wish to entirely exit the loop, skip an iteration, or ignore the...

3 minutes read.

Python Operator Precedence

Before knowing about the operator precedence in Python, we have to know about the operators in Python. So let's have a look at it. According to one definition, the operator is...

3 minutes read.

First Unique Character in a String Python

This article aims to introduce you to strings and how to create a string in Python, and then we will solve a simple yet exciting DSA (Data Structures and Algorithms)...

3 minutes read.

Captcha Code in Python with Example

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.

Salary of Python Developers in India

In this tutorial, we will understand who python developers are and what is their salary when they work in India. Python Developers Python Developers are the people who are involved in designing...

4 minutes read.

Python eval() function

Python eval() function The eval() function in Python is used to evaluate the given expression. If the specified expression is a legal Python statement, it will be executed. Syntax eval(expression, globals=None, locals=None) Parameter expression: This parameter represents a String,...

1 minute read.

File Explorer using Tkinter in Python

File Explorer: Users can control folders and files on a device using an application known as a file manager or file explorer. Customers can access, edit, copy, delete, and start moving files...

3 minutes read.

Adding item to a python dictionary

The dictionary is one of python’s built-in data structures where it stores key-value pairs. A dictionary is a collection of ordered values that can be changeable. We can add, modify,...

3 minutes read.

Python History

Python is one of the top trending, widely-used programming languages. Python is a general-purpose programming language. Python language is known for its features. Some features are given below: SimplisticFree and open...

4 minutes read.

Read Text files in Python

In Python, there are many ways to read text files. Before going into the detailed structure of reading a text file, let us understand how reading text files takes place...

4 minutes read.

Python Dictionary fromkeys() method

Python Dictionary fromkeys() method The dictionary.fromkeys() method in Python creates a new dictionary from the given sequence of elements and returns a dictionary with the specified keys and values. Syntax dictionary.fromkeys(sequence[, value]) Parameter sequence- This...

1 minute read.

Difference between Input() and raw_input() functions in Python

There are two input functions in Python that are used for taking input are given below: raw_input()input() What is raw_input() Function? raw_input() function is a built-in function in Python. It is used to...

6 minutes read.

What does base case mean in recursion

Base cases and recursive stages are used to define recursive functions. In a primary subject, we compute the outcome right away, given the function call's arguments. In a recursive step, we...

4 minutes read.

Python elif

Python elif The elif statement is used to check multiple conditions and execute the specific block of statements depending upon the true condition among them. Syntax if expression1: statement elif expression2: statement elif expression3: statement else: statement The elif statement can be optional...

3 minutes read.

Convert String to Binary in Python

String to binary The strings can be defined as the array of Unicode code characters. Binary Binary is defined as the number system which consists two symbols 0 and 101. It is base-2...

2 minutes read.