×

Python Time Library

  • We will consider various functions given by the python module library with examples.
  • This python time module helps to work on time in python to get the current time.
  • Before going with the example we have to import the library.

Import the time module:

  • There is no need to install any module we have just importedthem using the import statement.
import time

Epoch:

  • Where the time starts it is called epoch which is platform-dependent.
  • The epoch is January 1, 1970, 00:00:00 for windows and most Unix systems.
  • We can check the epoch using time.gmtime(0).
Import time
Print( time.gmtime(0) )

Output:

Time.strut_time (tm_year=1970, tm_mon=1,  tm_mday=1, tm.hour=0, tm_min=0,tn_sec=0,tm_wday=3, tm_yday=1, tm_isdst=0 )

Time.ctime

  • It is a function that returns a string of 24 characters, and time.
  • This function takes seconds as an argument and computes until the provided time.
  • If the argument is not provided then it will consider the current time and compute till the current time.

Consider an example of getting time in the form of string:

import time
/ / getting current time by passing 
/ / seconds passes since epoch
sec = 1545925769.9618232
current = time.ctime ( sec )
Print(“current time:”,current

Output:

Current time: Tue Aug 22 12:33:54 2022

Program Delaying Execution

  • The program execution can be delayed using time.sleep ( ) method.
  • For a specified amount of time program execution can be delayed by using this function.

Consider an example to implement the above scenario:

import time
for i in range (5):
/ / using the sleep method 
	time.sleep(2)
	print(i)

Output:

0
1
2
3
4

Time.struct_time Class

  • This function helps in accessing the local time which is non-epochal timestamps.
  • It returns a tuple with a name, where both index and attribute name is used to access the value.
  • The objects contain the attribute as follows:
IndexAttribute nameValues
0tm_year0000, ….., 9999
1tm_mon1,2,3,4,5,…. 11,12
2tm_mday1,2,3,…,30,31
3tm_hour0,1,2,3,4,….,21,22,23
4tm_min0, 1, 2, 3, …, 57, 58, 59
5tm_sec0, 1, 2, 3, …., 60, 61
6tm_wday0, 1, 2, 3, 4, 5, 6 ;6 is Sunday
7tm_yday1, 2, 3, 4, …, 365, 366
8tm_isdst0, 1 or -1

Python time.localtime ( )

  • This function returns struct time in local time, it takes a number of seconds from epoch as an argument.
  • If the argument is not given then time.time( ) is used.
  • Let us assume a program for the above scenario:
/ /import the time module
import time
/ / convert the time 
/ /from the epoch  
/ / time.strurct_time object in local time
obj = time.localtime(1545925769)
print(“Result:”,obj)
print(“/n Year:”,obj.tm_year)
print(“Hour:”obj.tm_hour)

Output:

Result: time.struct_time( tm_year=2022, tm_mo = 8, tm_mday = 3, tm_hour = 16, tm_min = 15,tm_sec = 8,tm_wday = 1,tm_yday = 215, tm_isdst = 0)
Year: 2022
Hour: 15

Python time.gmtime( )

  • This function returns the struct_time in UTC.
  • It takes a number of seconds from the epoch as an argument.
  • This function is used to convert seconds from epoch to struct time.
  • If the argument is not given then time.time( ) is used.
  • Let us consider an example program:
/ /importing the time module
import time
/ / convert the time in seconds
/ /since the epoch to a 
/ / time.struct_time object in local time
obj = time.gmtime(1545925769)
print(“Result:”,obj)
print(“/n Year:”,obj.tm_year)
print(“Hour:”obj.tm_hour)

Output:

Result: time.struct_time( tm_year=2022, tm_mo = 8, tm_mday = 3, tm_hour = 16, tm_min = 15,tm_sec = 8,tm_wday = 1,tm_yday = 215, tm_isdst = 0)
Year: 2022
Hour: 15

Python time.strptime ( )

  • This method converts the time which is in form of a string to struct time.
  • Let us consider a program for the above case:
/ /importing the time module
import time
/ / declare a variable with current date
time_string = “22 Aug 2022”
obj = time.strptime(time_string, “%d %B,%Y”)
/ / printing the object
print(obj)

Output:

time.struct_time( tm_year=2022, tm_mo = 8, tm_mday = 22, tm_hour = 0, tm_min = 0,tm_sec = 0,tm_wday = 1,tm_yday = 172, tm_isdst = -1)

Python time.mktime ( )

  • This function returns the seconds from the beginning of the epoch from local time.
  • The struct_time is taken as argument in the mktime( ) function.
  • The mktime( ) function is a inverse of localtime( ) function.
  • Let us consider a program for the above function:
/ / import the python time module
import time
/ / declaring a variable 
time = 1627988053
/ / returning the struct_time
obj1 = time.localtime( time ) 
print(“obj1:”, obj1 )
 / / returning the time in seconds from struct_time
obj = time.mktime( time )
print(“obj:”, obj )

Output:

Obj1 :time.struct_time( tm_year=2022, tm_mo = 8, tm_mday = 22, tm_hour = 0, tm_min = 0,tm_sec = 0,tm_wday = 1,tm_yday = 172, tm_isdst = -1)
Obj :1627988053

Python time.asctime( )

  • This function returns a string representing the time given.
  • The function asctime( ), takes struct_time as an argument.
  • It converts a struct_time in to string object which represents the time.
  • The return string is represented as:
    Day Mon Date Hour: Min: Sec Year
  • Let us consider an example program for the above function.
/ / import the python time module
import time
/ / declaring a variable 
sec = 1627988053
/ / convert the struct time 
/ / into string in the form “Day Mon Date Hour: Min: Sec Year”
/ / using the asc.time( ) function 
obj = time.gmtime( sec ) 
time_str = time.asctime( obj )
print( time_str)
/ / convert the struct time 
/ / into string in the form “Day Mon Date Hour: Min: Sec Year”
/ / using the asc.time( ) function 
Obj1 = time.localtime( sec )
time_str = time.asctime( obj )
print(time_str )

Output:

Mon Aug 22 10:23:09 2022
Mon Aug 22 10:23:09 2022

Python time.strftime( )

  • This function returns a string representing the time given.
  • The function strftime( ), takes struct_time as an argument.
  • The string which the function returns is based on the format codes.
  • Let us consider a program for the above function:
/ / import the python time module
import time
/ / declaring a variable
obj = time.local time( )
/ / converting the time in a string using the strf.time ( ) function
stringobj = time.strftime ( “%m %d %Y, %H : %M : %S “, obj )
/ / displaying the time
print( stringobj )

Output:

08/22/2022, 09: 23: 34

Related Topics

Python all() Function

Python all() Function The all() function in Python returns a Boolean value ‘True’ if all the items in iterable are true or if the iterable object is empty, else it returns False. Syntax all(iterable) Parameter Iterable: An iterable object...

1 minute read.

Python program to find the greatest among two numbers

Python program to find the greatest among two numbers We have many approaches to get the largest number among the two numbers, and here we will discuss a few of them....

2 minutes read.

Python Dictionary pop() method

Python Dictionary pop() method The dictionary.pop() method in removes the specified item and returns an element from a dictionary having the given key. Syntax dictionary.pop(key[, default]) Parameter key – This argument signifies the key which is to...

2 minutes read.

Python Project Ideas for Beginners

Python project ideas for beginners Advanced Python is an amazing platform to grow and achieve success as a developer in the future. Python is a programming language that can be very...

7 minutes read.

Assertion Errors and Attribute Errors in Python

Assertion Error in Python In Python, the assert condition is used to continue the execution if the given statement displays true. If the assert statement displays false, it raises Assertion Error...

3 minutes read.

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...

6 minutes read.

Python String decode() method

Python String decode() method The string.decode() method decodes the string using the codec registered for encoding. Default encoding is the current default string encoding. It may raise errors to set a different error handling...

1 minute read.

Python String index() method

Python String index() method The string.index() method in Python finds the lower index of the first occurrence of the specified value or raise a ValueError if the substring is not found. Syntax index(sub[, start[, end]]) Parameter sub:...

2 minutes read.

Python Keywords

If you are trying to learn a programming language, you need to have a basic idea of "What are keywords" and "How they are used". You can learn about keywords in...

7 minutes read.

Python Indentation

Overview The spaces at the start of a code line are known as an indentation in Python programming. Indentation is only used for readability in other programming languages like C, C++,...

8 minutes read.

Word frequency Python

Word frequency Python In this tutorial, we will write the Python program to count the occurrence of a word (word frequency) in a given sentence. We will learn all the approaches...

5 minutes read.

Cube Root in Python

In general, the cube is a three-dimensional solid figure that has 6 square faces. It is also called a geometrical shape with six equal faces, eight vertices, and twelve edges....

3 minutes read.

Looping through Data Frame in Python

Iterate over Rows and Columns in Pandas Dataframe This tutorial aims to make us understand what Pandas in Python are, what Data Frame in Python is and its significance, what are...

4 minutes read.

Returning Multiple Values in Python

Python is considered a general-purpose programming language; it is a high-level programming language that is not much difficult and easier to learn. It is rich in libraries that can be...

3 minutes read.

Python type() Function

Python type() Function The type() function in Python returns the type of an object. The return value is a type object and generally the same object as returned by object.__class__. Syntax class type(object)      ...

1 minute read.

Best books for NLP with Python

NLP NLP – Natural language processing Computers were created to make the life of mankind easier. But computers cannot understand human language. Instead, they interact with numbers to perform the tasks allotted...

12 minutes read.

Python String isspace() method

Python String isspace() method The string.isspace() method returns a Boolean value true if there are only whitespace characters in the given string. This function is used to check if the given...

2 minutes read.

Python Virtual Environment

In this tutorial, we will understand Virtual Environment in Python. We will understand the need for a virtual environment and also see how to make use of it in python....

3 minutes read.

Bar Plot in Python

A bar chart or bar graph displays categorical data using rectangular bars with heights or lengths proportionate to the values for the data distributed in the dataset. In a bar...

16 minutes read.

Get index of element in array in python

Index : Index is a number where the element is located in the given list. In other words it is the position of the element in the list. Index can also...

4 minutes read.