The time module with its functions and examples in the Python programming language.
Python time Module
The time module is an integrated module in Python that has several features for time. For example, you can get the current date and time.
To use the time module, you have to import the time module (Python has many modules that let you build your program).
This module starts the time from the time of the recording. Epoch is history, beginning 1 January 1970. Epoch is history.
time()
The epoch time is returned by this function.
Python Example:
# Import time module
import time
s=time.time()
print('Total seconds since epoch:',s)
The program above outputs this:
Total seconds since epoch: 1576083939.5877264
This works in both the shell and in a script
ctime()
This Python function of the time module takes second as an argument and return time until the mentioned seconds.
Python Example:
# Import time module
import time
st=1575293263.821704
current_time=time.ctime(st)
print('time since epoch:',current_time)
The program above outputs this:
time since epoch: Mon Dec 2 14:27:43 2019
sleep()
This function is used to pause the execution of the program for the time specified in the arguments.
Python Example:
# Import time module
import time
print('Execution start time:',time.ctime())
time.sleep(5)
print('End execution time:',time.ctime())
The program above outputs this:
Execution start time: Tue Jun 9 16:40:56 2020
End execution time: Tue Jun 9 16:41:01 2020
strftime()
The strftime() function takes an argument and returns a string.
Python Example:
# Import time module
import time
now_time=time.localtime()
tif=time.strftime("%m/%d/%Y, %H:%M:%S",now_time)
print('The time since epoch:',tif)
The program above outputs this:
The time since epoch: 06/09/2020, 16:42:25
asctime()
The asctime() function takes a tuple of length nine as an argument and returns a string.
Python Example:
# Import time module
import time
t=(2020,3,5,2,20,1,5,365,0)
r=time.asctime(t)
print("Time and date is:",r)
The program above outputs this:
Time and date is: Sat Mar 5 02:20:01 2020
Top comments (0)