The time
module in Python is used to calculate elapsed time in seconds.
The general syntax is:
time
moduleimport time
time
module functionsFunction 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])
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)
sleep
methodThe 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