What is the Python time module?

The time module in Python is used to calculate elapsed time in seconds.

Syntax

The general syntax is:

  1. Import the time module
import time
  1. Use the time module functions
Function Name Description
time.time() calculates the time elapsed from 1917 (the beginning of time in computers) in seconds
time.asctime() calculates the current time
time.gmtime() calculates the greenwich mean time
time.sleep(n) n is the number of seconds for which the program goes to sleep
import time
print(time.time())
print("Current time:",time.asctime())
print("Greenwich mean time:",time.gmtime())
# To access one particular value from Greenwich Mean Time
value=time.gmtime()
print(value[2])

Example 1: Calculate the time for code execution

Using the time module it is possible to calculate the time it takes for a piece of code to execute.

Take two time values, one at the start of your code execution and another at the end. By subtracting the second value from the first, you will get the execution time of the code. The following code shows how it can be done:

import time
start= time.time()
a=1
b=2
c=a+b
print(c)
stop=time.time()
print(stop-start)

Example 2: Calculate the time for code execution using sleep method

The code stops executing for n number of seconds passed as a parameter to time.sleep. The following code shows how it can be done:

import time
start= time.time()
a=1
b=2
c=a+b
print(c)
time.sleep(2)
stop=time.time()
print(stop-start)

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved