Python Time Module
The time module provides various time-related functions. It is commonly used for measuring execution time, suspending execution, and formatting time.
Importing the Module
import time
Getting Current Time
time.time()
Returns the current time in seconds since the Epoch (January 1, 1970, 00:00:00 (UTC)).
import time
seconds = time.time()
print("Seconds since epoch =", seconds)
time.ctime()
Returns a string representing the current time.
import time
local_time = time.ctime()
print("Local time:", local_time)
Suspending Execution
time.sleep()
Suspends execution of the calling thread for the given number of seconds.
import time
print("Start")
time.sleep(2)
print("End")
Formatting Time
time.strftime()
Converts a struct_time object (like that returned by time.localtime()) to a string according to a format specification.
import time
named_tuple = time.localtime() # get struct_time
time_string = time.strftime("%m/%d/%Y, %H:%M:%S", named_tuple)
print(time_string)
Performance Counters
time.perf_counter()
Returns the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration.
import time
start = time.perf_counter()
# ... do something ...
time.sleep(1)
end = time.perf_counter()
print(f"Elapsed time: {end - start}")