Python Date and time

Python Time Module (with Examples)

Working with time is an important aspect of many applications. Assume you’re creating a sign-up form for a website. You might wish to get the current time so you know when a user joined your site. This is where the Python time module comes into play. You can use the time module in your Python scripts to work with time. You can do actions such as retrieving the current time, waiting during code execution, and measuring the efficiency of your code. In this tutorial, we will look in-depth at the Python time module. With the help of examples, we will learn how to use the many time-related functions defined in the time module.

Python time module

To handle time-related tasks, Python has a module called time. The time module is a standard Python module that offers functions for accessing and converting time. To use the module’s functionalities, we must first import the Python time module.

The beginning of time is measured from 1 January, 12:00 a.m., 1970, and this time is referred to as the “epoch” in Python. It should be noted that this module has limits; for example, the functions may not handle dates and times before to the epoch or in the remote future.

Python time module functions

The Python time module provides a wide range of functions for dealing with time stamps. Let us understand a few of them along with their examples.

  • Python time.time()

The time() method in Python returns the current time. It returns the number of seconds that have passed since the epoch. Assume we want to find out what time it is right now. We could achieve that by using the following program:

                    

import time

seconds = time.time()
print('Seconds since epoch =', seconds)

Output

                    

Seconds since epoch = 1634760477.7176368

  • Python time.ctime()

Most humans are unable to read epoch time. The Python ctime() method can be used to convert time from epoch to local time. The ctime() function takes a single argument. The time.ctime() function takes an argument of seconds since the epoch and returns a string representing local time.

                    

import time

# seconds passed since epoch
seconds = 1634760597.7176368

local_time = time.ctime(seconds)
print('Local time:', local_time)

Output

                    

Local time: Wed Oct 20 20:09:57 2021

  • Python time.sleep()

This is a pretty intriguing time module function. The  time.sleep() suspends a program’s execution for a specified number of seconds. The sleep() function suspends (delays) the current thread’s execution for the specified amount of seconds. The time.sleep() function accepts floating-point (decimal) or integer (whole) number values. If we want to print the sentences after a few seconds, we can do so using the following method:

                    

import time

print('This is printed immediately')

time.sleep(3)
print('This is printed after 3 seconds')

time.sleep(3)
print('This is printed after 3 more seconds')

Output

                    

This is printed immediately
This is printed after 3 seconds
This is printed after 3 more seconds

Python time.struct_time Class

Several functions in the time module, such as gmtime(), asctime(), localtime(), and so on, either take or return the time.struct_time object. Python’s time.struct time is a class. Many time functions return values in time.struct_time format. The syntax of the time.struc_time object is as follows:

                    

time.struct_time(tm_year=2021, tm_mon=10, tm_mday=20,
                    tm_hour=11, tm_min=40, tm_sec=17,
                    tm_wday=4, tm_yday=301, tm_isdst=0)

The following are the values that the struct_time object can store:

Index Attribute Description Values
0 tm_year Year 0000, ….., 2021, …, 9999
1 tm_mon Month 1, 2, …, 12
2 tm_mday Day of the month 1, 2, …, 31
3 tm_hour Hour 0, 1, …, 23
4 tm_min Minute 0, 1, …, 59
5 tm_sec Second 0, 1, …, 61
6 tm_wday Day of the week 0, 1, …, 6; Monday is 0
7 tm_yday Day of the year 1, 2, …, 366
8 tm_isdst Time in daylight savings time 0, 1 or -1
  • Python time.localtime()

Let’s say we want to convert epoch time to local time and have the result be a struct time object. We could use either the localtime() or gmtime() functionalities to accomplish this. The localtime() function accepts as an input the amount of seconds since the epoch and returns struct time in local time. It allows us to access the various fields of a local time-stamp, such as the year, hour, seconds, and so on.

                    

import time

result = time.localtime(1634799170)
print('Result:', result)

print('\ntm_year:', result.tm_year)
print('tm_hour:', result.tm_hour)
print('tm_yday:', result.tm_yday)

Output

                    

Result: time.struct_time(tm_year=2021, tm_mon=10, tm_mday=21, 
tm_hour=6, tm_min=52, tm_sec=50, tm_wday=3, tm_yday=294, tm_isdst=0)

tm_year: 2021
tm_hour: 6
tm_yday: 294

  • Python time.gmtime()

The gmtime() function, like the localtime() function, returns a struct time object from an epoch time. It accepts an argument of the amount of seconds since the epoch and returns struct time in UTC. If gmtime() is called with no arguments or None, the value returned by time() is utilised.

                    

import time

current_time = time.gmtime(1634799150)
print('Current Year:', current_time.tm_year)
print('Month of the year:', current_time.tm_mon)
print('Day of the month:', current_time.tm_mday)

Output

                    

Current Year: 2021
Month of the year: 10
Day of the month: 21

  • Python time.mktime()

The inverse of the time.localtime() method is time.mktime(). It accepts the struct time (all the struct time tuples) as an argument and returns the time in seconds that has elapsed/passed since the epoch.

                    

import time

t = (2021, 10, 21, 6, 52, 30, 4, 294, 0)

local_time = time.mktime(t)
print('Local time:', local_time)

Output

                    

Local time: 1634799150.0

  • Python time.asctime()

The asctime() method accepts struct time (or a tuple of 9 elements corresponding to struct time) as an argument and returns a string representation of it.

                    

import time

t = (2021, 10, 21, 8, 55, 8, 4, 294, 0)
 
local_time = time.asctime(t)
print('Local time:', local_time)

Output

                    

Local time: Fri Oct 21 08:55:08 2021

  • Python time.strftime()

The inverse of the time.strptime() method is time.strftime(). It accepts struct time class tuples as arguments and returns a string indicating the time based on the supplied format codes. Assume we want to convert a struct time object to a string with the following format: Month/Day/Year and Hours/Minutes/Seconds. We could achieve such by using the following code:

                    

import time

current_time = time.localtime()   # get struct_time
time_string = time.strftime("%m/%d/%Y, %H:%M:%S", current_time)

print(time_string)

Output

                    

10/21/2021, 08:59:20

  • Python time.strptime()

The time.strptime() method receives a time string and returns the time data in the struct time format.

                    

import time

time_string = '21 October, 2021'
result = time.strptime(time_string, '%d %B, %Y')

print(result)

Output

                    

time.struct_time(tm_year=2021, tm_mon=10, tm_mday=21, tm_hour=0, 
tm_min=0, tm_sec=0, tm_wday=3, tm_yday=294, tm_isdst=-1)

Frequently Asked Questions

Q1. What is Python time?

To handle time-related tasks, Python has a module called time. The time module is a standard Python module that offers functions for accessing and converting time. To use the module’s functionalities, we must first import the Python time module.

You can use the time module in your Python scripts to work with time. You can do actions such as retrieving the current time, waiting during code execution, and measuring the efficiency of your code.

Q2. How do you wait 5 seconds in Python?

The  time.sleep() suspends a program’s execution for a specified number of seconds. The sleep() function suspends (delays) the current thread’s execution for the specified amount of seconds. The time.sleep() function accepts floating-point (decimal) or integer (whole) number values.

                    

import time

# printing the start time
print('This statement is printed at: ', end='')
print(time.ctime())

# using sleep() to hault the code execution
time.sleep(5)

# printing the next statement
print('This statement is printed at: ', end='')
print(time.ctime())

time.sleep(5)
print('This statement is printed at: ', end='')
print(time.ctime())

Output

                    

This statement is printed at: Thu Oct 21 09:33:54 2021
This statement is printed at: Thu Oct 21 09:33:59 2021
This statement is printed at: Thu Oct 21 09:34:04 2021

Q3. How do you add time in Python?

We make use of datetime.timedelta(hours) function in Python for adding time with hours set to the required added hours to convert hours to a datetime.timedelta object. Include the current datetime.datetime object containing the previous datetime.timedelta to generate a new datetime.datetime object with the extra hours.

                    

import datetime

current_date_and_time = datetime.datetime.now()
print(current_date_and_time)

hours = 5
hours_added = datetime.timedelta(hours = hours)
 
future_date_and_time = current_date_and_time + hours_added
print(future_date_and_time)

Output

                    

2021-10-21 09:38:48.594611
2021-10-21 14:38:48.594611

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

Your email address will not be published. Required fields are marked *

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.