What is the Python time module?
The time module in Python is used to calculate elapsed time in seconds.
Syntax
The general syntax is:
- Import the
timemodule
import time
- Use the
timemodule 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 timeprint(time.time())print("Current time:",time.asctime())print("Greenwich mean time:",time.gmtime())# To access one particular value from Greenwich Mean Timevalue=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 timestart= time.time()a=1b=2c=a+bprint(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 timestart= time.time()a=1b=2c=a+bprint(c)time.sleep(2)stop=time.time()print(stop-start)
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved