×

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

Find Words in String Python

Python : Python programming language is considered a general purpose; it is a high-level programming language that is not much difficult but easier to learn. Python programming language is rich in...

5 minutes read.

Assignment Operators in Python

The prime usage of Assignment Operators is to assign values to variables. These are taken into account to do operations on values and variables. There are some special symbols in python...

4 minutes read.

Standard Scalar in Python

Python is a vast and open-source language that contains many libraries, modules, and functions. These functions in python are reusable codes where we don’t need to type the whole code...

4 minutes read.

GUI Calendar using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

3 minutes read.

How to create a file in Python?

How to create a file in python? Files provide us a convenient way of storing our information. Once we have our data, the next task is to store it so that...

3 minutes read.

How to import numy in python

How to Install NumPy in Python Python is a vast ocean of libraries, modules, and different functions. It has a solution for almost everything. Using Python, we can simplify even a...

3 minutes read.

Python hash() function

Python hash() function The hash() function in Python returns the hash value of the object (if it has one).  Syntax hash(object) Parameter obj : This parameter represents the object which we need to convert into hash. Return This...

1 minute read.

Polymorphism in Python

What is polymorphism and why is it important? Polymorphism's literal definition is the state of occurring in diverse shapes or forms. When it comes to programming, the idea of polymorphism is crucial....

3 minutes read.

How to write a program in python?

How to write a program in python? In python, writing programs is not a big deal. What we need to work on is our logic and some basic rules of this...

4 minutes read.

Python Escape Characters

In this tutorial, we will learn how to use the Escape Characters in Python. Escape Character: Escape Characters are used for some special meaning in our statements. It is denoted or represented...

3 minutes read.

Python isinstance() function

Python isinstance() function The isinstance() function in Python returns a Boolean value ‘True’ if the given object is of the specified type, otherwise it returns False. Syntax isinstance(object, classinfo) Parameter object: It is a required parameter which represents an object. classinfo: This...

1 minute read.

Python Tuple count() Method

Python Tuple count() Method The tuple.count() method in Python returns the number of times a specified value appears in the tuple. Syntax tuple.count(value) Parameter value- This parameter represents the element to search in the tuple Return This...

1 minute read.

Python String Negative Indexing

This page contains all the information how to use “Negative indexing“ in Python with the help of using slicing. What is an Index? An index is a numeric value, which is assigned...

3 minutes read.

Anytree Python

Python's anytree module is frequently used within data science-related software. Anytree has a Tolerant License, a Construct File that is public, no errors, no risks, and excellent support. One may...

3 minutes read.

Loan calculator using Tkinter in Python

Tkinter: Tkinter, part of all common Python distributions, is the de facto method for creating Graphical User Interfaces (GUIs) in Python. The only framework included in the Python standard library is...

4 minutes read.

Hypothesis Testing in Python

Hypothesis Testing in python is widely used along with statistics. Many libraries in Python are very useful for statistics and machine learning. Libraries like numpy, scripy etc. help in hypothesis testing in...

12 minutes read.

How to set up a proxy using selenium in python

What is Proxy? A proxy acts as a middleman between user requests and server responses. The main purposes of proxies are to protect user privacy and encapsulate data between various interactive...

3 minutes read.

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.

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.

Run exec python from PHP

PHP (which is a recursive abbreviation for PHP Hypertext Preprocessor) is one of the most broadly involved web improvement innovations on the planet. PHP code utilized for creating sites and...

4 minutes read.