Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

timer
python
clock

What is the Python time module?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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)

RELATED TAGS

timer
python
clock
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring