The Wayback Machine - https://web.archive.org/web/20240930233403/https://www.geeksforgeeks.org/python-time-module/
Open In App

Python Time Module

Last Updated : 13 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will discuss the time module and various functions provided by this module with the help of good examples. 

As the name suggests Python time module allows to work with time in Python. It allows functionality like getting the current time, pausing the Program from executing, etc. So before starting with this module, we need to import it. 

Importing time module

The time module comes with Python’s standard utility module, so there is no need to install it externally. We can simply import it using the import statement.

import time

What is epoch?

The epoch is the point where the time starts and is platform-dependent. On Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC), and leap seconds are not counted towards the time in seconds since the epoch. To check what the epoch is on a given platform we can use time.gmtime(0).

Example: Getting epoch

The code uses the time module to print the result of time.gmtime(0), which represents the time in the GMT (Greenwich Mean Time) timezone at the Unix epoch (January 1, 1970, 00:00:00 UTC).

Python
import time
print(time.gmtime(0))

Output:

time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)

Note: The time before the epoch can still be represented in seconds but it will be negative. For example, 31 December 1969 will be represented as -86400 seconds.

Getting current time in seconds since epoch

time.time() methods return the current time in seconds since epoch. It returns a floating-point number.

Example: Current time in seconds since epoch

The code uses the time module to retrieve the current time in seconds since the Unix epoch (January 1, 1970).

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

Output
Current time in seconds since epoch = 1627908387.764925

Getting time string from seconds

time.ctime() function returns a 24 character time string but takes seconds as argument and computes time till mentioned seconds. If no argument is passed, time is calculated till the present.

Example: Getting time string from seconds

The code uses the time module to convert a specified timestamp (1627908313.717886) into a human-readable date and time format.

Python
import time
curr = time.ctime(1627908313.717886)
print("Current time:", curr) 

Output
Current time: Mon Aug  2 12:45:13 2021

Delaying Execution of Programs

Execution can be delayed using time.sleep() method. This method is used to halt the program execution for the time specified in the arguments.

Example: Delaying execution time of programs in Python.

This code uses the time module to introduce a one-second delay using time.sleep(1) inside a loop that iterates four times.

Python
import time
for i in range(4):
    time.sleep(1)
    print(i)

Output
0
1
2
3

time.struct_time Class

Struct_time class helps to access local time i.e. non-epochal timestamps. It returns a named tuple whose value can be accessed by both index and attribute name. Its object contains the following attributes – 

Index Attribute Name Values
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 contains various functions. Let’s discuss each function in detail.

time.localtime() method

localtime() method returns the struct_time object in local time. It takes the number of seconds passed since epoch as an argument. If the seconds parameter is not given then the current time returned by time.time() method is used.

Example: Getting local time from epoch

The code uses the time module to convert a specified timestamp (1627987508.6496193) into a time.struct_time object representing the corresponding date and time.

Python
import time
obj = time.localtime(1627987508.6496193)
print(obj)

Output

time.struct_time(tm_year=2021, tm_mon=8, tm_mday=3, tm_hour=16, tm_min=15, tm_sec=8, tm_wday=1, tm_yday=215, tm_isdst=0)

time.mktime() method

time.mktime() is the inverse function of time.localtime() which converts the time expressed in seconds since the epoch to a time.struct_time object in local time.

Example: Converting the struct_time object to seconds since epoch

This code first uses the time module to convert a specified timestamp (1627987508.6496193) into a time.struct_time object in the GMT (Greenwich Mean Time) timezone using time.gmtime(). Then, it uses time.mktime() to convert this time.struct_time object back into a timestamp.

Python
import time
obj1 = time.gmtime(1627987508.6496193)
time_sec = time.mktime(obj1)
print("Local time (in seconds):", time_sec)

Output
Local time (in seconds): 1627987508.0

time.gmtime() method

time.gmtime() is used to convert a time expressed in seconds since the epoch to a time.struct_time object in UTC in which tm_isdst attribute is always 0. If the seconds parameter is not given then the current time returned by time.time() method is used.

Example: Use of time.gmtime() method

The code uses the time module to convert a specified timestamp (1627987508.6496193) into a time.struct_time object representing the corresponding date and time in the GMT (Greenwich Mean Time) timezone.

Python
import time
obj = time.gmtime(1627987508.6496193)
print(obj)

Output

time.struct_time(tm_year=2021, tm_mon=8, tm_mday=3, tm_hour=10, tm_min=45, tm_sec=8, tm_wday=1, tm_yday=215, tm_isdst=0)

time.strftime() method

time.strftime() function converts a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string as specified by the format argument. If t is not provided, the current time as returned by localtime() is used. The format must be a string. ValueError is raised if any field in t is outside of the allowed range.

Example: Converting struct_time object to a string using strftime() method

The code uses the gmtime function from the time module to convert a specified timestamp (1627987508.6496193) into a formatted string using strftime. The output represents the date and time in the GMT (Greenwich Mean Time) timezone in the format specified by the format string.

Python
from time import gmtime, strftime
s = strftime("%a, %d %b %Y %H:%M:%S", 
             gmtime(1627987508.6496193))
print(s)

Output
Tue, 03 Aug 2021 10:45:08

time.asctime() method

time.asctime() method is used to convert a tuple or a time.struct_time object representing a time as returned by time.gmtime() or time.localtime() method to a string of the following form:

Day Mon Date Hour:Min:Sec Year

Example: Converting tuple to time.struct_time object to string

This code uses the time module to convert a specified timestamp (1627987508.6496193) into a human-readable date and time format using time.asctime(). It does so both for the GMT (Greenwich Mean Time) timezone and the local timezone.

Python
import time
obj = time.gmtime(1627987508.6496193)
time_str = time.asctime(obj)
print(time_str)
obj = time.localtime(1627987508.6496193)
time_str = time.asctime(obj)
print(time_str)

Output
Tue Aug  3 10:45:08 2021
Tue Aug  3 10:45:08 2021

time.strptime() method

time.strptime() method converts the string representing time to the struct_time object.

Example: Converting string to struct_time object.

This code uses the time module to parse a formatted string representing a date and time and convert it into a time.struct_time object. The time.strptime() function is used for this purpose.

Python
import time
string = "Tue, 03 Aug 2021 10:45:08"
obj = time.strptime(string, "%a, %d %b %Y %H:%M:%S")
print(obj)

Output

time.struct_time(tm_year=2021, tm_mon=8, tm_mday=3, tm_hour=10, tm_min=45, tm_sec=8, tm_wday=1, tm_yday=215, tm_isdst=-1)

Python Time Module – FAQs

What is Module Time in Python?

The time module in Python provides various functions for working with time, including pausing program execution and retrieving the current time. The functions in this module handle time-related tasks, such as converting between different time representations (e.g., seconds since the epoch to a structured time.struct_time object), measuring time intervals, and implementing delays.

What is time() in Python?

time() is a function in the Python time module that returns the current time in seconds since the epoch as a floating point number. The epoch is defined as the point where the time starts, and it is platform-dependent. For Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC). You can use this function to timestamp events or measure durations.

import time

current_time = time.time()
print("Current time in seconds since the epoch:", current_time)

How to Install Time Module in Python?

The time module is part of the Python Standard Library, which means it comes pre-installed with Python and does not require any additional installation. You can directly import and use it in your Python scripts without any setup.

What is %%time?

%%time is not a Python command but a magic command for Jupyter Notebooks and IPython environments. It is used to measure the execution time of a single cell in a Jupyter Notebook. When you place %%time at the top of a cell, it reports the time taken to execute the cell.

%%time
# Example of using %%time in a Jupyter Notebook cell
import time
time.sleep(2) # Sleep for 2 seconds

What is time.sleep() in Python?

time.sleep() is a function in the time module that pauses the execution of the program for the specified number of seconds. The argument can be a floating point number to indicate more precise sleep times (like fractions of a second). This function is useful for delaying actions, throttling CPU usage, or simulating delays in your programs.

import time

print("Start")
time.sleep(5) # Sleep for 5 seconds
print("End after 5 seconds")

Using these time-related functionalities allows you to manage time and delays in your Python applications effectively, whether for handling real-time data, creating pauses in games and simulations, or synchronizing events



Similar Reads

Time difference between expected time and given time
Given the initial clock time h1:m1 and the present clock time h2:m2, denoting hour and minutes in 24-hours clock format. The present clock time h2:m2 may or may not be correct. Also given a variable K which denotes the number of hours passed. The task is to calculate the delay in seconds i.e. time difference between expected time and given time. Ex
5 min read
Pandas Series dt.time | Extract Time from Time Stamp in Series
The Series.dt.time attribute returns a NumPy array containing time values of the timestamps in a Pandas series. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_datetime
2 min read
Manipulate Date and Time with the Datetime Module in Python
Have you ever wondered about working with Date and Time with Python? If you have then you must have noticed that Python does not provide any built-in method to work with either Date or Time. But thanks to the DateTime module that comes pre-loaded with Python's standard utility modules we can easily manipulate date and time according to our own need
9 min read
Date Time Expression (dte) module in python
In this article, we will discuss how to process and work with dates and time using the Python in command line. Python provides dte module for the same. This module has the following features - It recognizes english month, week and locale names.It works in the highest unit appearing first - 2021 - 12 -24 ( yyyy-MM-dd ).Installation This module does
2 min read
Time Functions in Python | Set 1 (time(), ctime(), sleep()...)
Python has defined a module, "time" which allows us to handle various operations regarding time, its conversions and representations, which find its use in various applications in life. The beginning of time started measuring from 1 January, 12:00 am, 1970 and this very time is termed as "epoch" in Python. Operations on Time in Python Python time.t
4 min read
Python | time.time() method
Time module in Python provides various time-related functions. This module comes under Python’s standard utility modules. time.time() method of Time module is used to get the time in seconds since epoch. The handling of leap seconds is platform dependent. Note: The epoch is the point where the time starts, and is platform dependent. On Windows and
2 min read
How To Highlight a Time Range in Time Series Plot in Python with Matplotlib?
A time series plot is a plot which contains data which is being measured over a period of time, for example, a gross domestic product of a country, the population of the world and many other data. Sometimes we want to highlight a specific period of the timeline so that it is easier for the observer to read specific data. We can highlight a time ran
4 min read
MySQL-Connector-Python module in Python
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
2 min read
twitter-text-python (ttp) module - Python
twitter-text-python is a Tweet parser and formatter for Python. Amongst many things, the tasks that can be performed by this module are : reply : The username of the handle to which the tweet is being replied to. users : All the usernames mentioned in the tweet. tags : All the hashtags mentioned in the tweet. urls : All the URLs mentioned in the tw
3 min read
MoviePy – Changing Image and Time at same time of Video Clip
In this article we will see how we can change display frames and time line of the video file clip in MoviePy at a same time. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF's. We use fl_image method to alter the display frames and fl_time method to alter the time, although we can do these task
2 min read
Python calendar module : formatmonth() method
Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. class calendar.TextCalendar(firstweekday=0) can be used to generate plain text
2 min read
Python | Writing to an excel file using openpyxl module
Prerequisite : Reading an excel file using openpyxl Openpyxl is a Python library for reading and writing Excel (with extension xlsx/xlsm/xltx/xltm) files. The openpyxl module allows Python program to read and modify Excel files. For example, user might have to go through thousands of rows and pick out few handful information to make small changes b
3 min read
Stack and Queue in Python using queue Module
A simple python List can act as queue and stack as well. Queue mechanism is used widely and for many purposes in daily life. A queue follows FIFO rule(First In First Out) and is used in programming for sorting and for many more things. Python provides Class queue as a module which has to be generally created in languages such as C/C++ and Java. 1.
3 min read
PyMsgBox module in Python
PyMsgBox is simple, cross-platform, purely implemented in Python for message boxes as JavaScript has. It uses Python's built-in Tkinter module for its GUI. Installation This module does not built-in Python. To install it type the below command in the terminal. pip install PyMsgBox There are four functions in PyMsgBox, which follow JavaScript’s mess
2 min read
uniform() method in Python Random module
uniform() is a method specified in the random library in Python 3. Nowadays, in general, day-day tasks, there's always the need to generate random numbers in a range. Normal programming constructs require a method more than just one word to achieve this particular task. In python, there's an inbuilt method, "uniform()" which performs this task with
2 min read
mode() function in Python statistics module
The mode of a set of data values is the value that appears most often. It is the value at which the data is most likely to be sampled. A mode of a continuous probability distribution is often considered to be any value x at which its probability density function has a local maximum value, so any peak is a mode.Python is very robust when it comes to
5 min read
median_low() function in Python statistics module
Median is often referred to as the robust measure of the central location and is less affected by the presence of outliers in data. statistics module in Python allows three options to deal with median / middle elements in a data set, which are median(), median_low() and median_high(). The low median is always a member of the data set. When the numb
4 min read
median_high() function in Python statistics module
Median is often referred to as the robust measure of the central location and is less affected by the presence of outliers in data. statistics module in Python allows three options to deal with median / middle elements in a data set, which are median(), median_low() and median_high(). The high median is always a member of the data set. When the num
4 min read
median_grouped() function in Python statistics module
Coming to Statistical functions, median of a data-set is the measure of robust central tendency, which is less affected by the presence of outliers in data. As seen previously, medians of an ungrouped data-set using median(), median_high(), median_low() functions. Python gives the option to calculate the median of grouped and continuous data functi
4 min read
stdev() method in Python statistics module
Statistics module in Python provides a function known as stdev() , which can be used to calculate the standard deviation. stdev() function only calculates standard deviation from a sample of data, rather than an entire population. To calculate standard deviation of an entire population, another function known as pstdev() is used. Standard Deviation
5 min read
Python | ASCII art using pyfiglet module
pyfiglet takes ASCII text and renders it in ASCII art fonts. figlet_format method convert ASCII text into ASCII art fonts. It takes following arguments : text font ( DEFAULT_FONT = 'standard' ) Command to install pyfiglet module : pip install pyfiglet Code #1: Text in default font # import pyfiglet module import pyfiglet result = pyfiglet.figlet_fo
6 min read
easyinput module in Python
easyinput module in Python offers an easy input interface analogous to cin stream in C++. It supports multiple data types including files and provides functionalities such as input till different data types, multi-line input, etc. Installation To install this module type the below command in the terminal. pip install easyinputFunction Usedread(*typ
3 min read
Python | Adjusting rows and columns of an excel file using openpyxl module
Prerequisites : Excel file using openpyxl writing | reading Set the height and width of the cells:Worksheet objects have row_dimensions and column_dimensions attributes that control row heights and column widths. A sheet’s row_dimensions and column_dimensions are dictionary-like values; row_dimensions contains RowDimension objects and column_dimens
3 min read
Python | Plotting charts in excel sheet using openpyxl module | Set - 1
Prerequisite: Reading & Writing to excel sheet using openpyxl Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Let's see how to plot different charts using realtime data. Charts are composed of at least one series of one or more data poi
6 min read
Python | Plotting charts in excel sheet using openpyxl module | Set – 2
Prerequisite: Python | Plotting charts in excel sheet using openpyxl module | Set – 1 Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Charts are composed of at least one series of one or more data points. Series themselves are comprised of
6 min read
Python | Plotting charts in excel sheet using openpyxl module | Set 3
Prerequisite : Plotting charts in excel sheet using openpyxl module Set - 1 | Set – 2Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Charts are composed of at least one series of one or more data points. Series themselves are comprised of r
7 min read
Python | Create and write on excel file using xlsxwriter module
XlsxWriter is a Python module for writing files in the XLSX file format. It can be used to write text, numbers, and formulas to multiple worksheets. Also, it supports features such as formatting, images, charts, page setup, auto filters, conditional formatting and many others.Use this command to install xlsxwriter module: pip install xlsxwriter Not
3 min read
spwd module in Python
spwd module in Python provides access to the Unix shadow password database. The entries stored in the database is tuple-like objects whose attributes are similar as the members of spwd structure defined in <shadow.h> header file. Following are the attributes of tuple-like object which represents the entries stored in Unix shadow password data
5 min read
Pygorithm module in Python
Pygorithm module is a Python module written purely in Python and for educational purposes only. One can get the code, time complexities and much more by just importing the required algorithm. It is a good way to start learning Python programming and understanding concepts. Pygorithm module can also help to learn the implementation of all major algo
2 min read
Python | Plotting Area charts in excel sheet using XlsxWriter module
Prerequisite: Create and write on an excel file XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different charts using realtime data. Charts are composed of at least one series of one or more data points. Series the
6 min read
Practice Tags :