The time
module in Python gives access to various time-related functions, including formatting time strings, sleep functions, timestamp conversions, and more.
Here are some examples of how you can use the time
module:
Getting the Current Time in Seconds
import time
current_time = int(time.time())
print(current_time)
Formatting Time Strings
import time
current_time = int(time.time())
formatted_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(current_time))
print(formatted_time)
Pausing Execution for a Given Amount of Time
import time
print("Starting process...")
time.sleep(3)
print("Finished process!")
Here are a couple more examples for using the time
module:
Converting a Timestamp to a Formatted String
import time
timestamp = 1629107042.0
formatted_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))
print(formatted_time)
This code takes a timestamp (as a floating-point number) and converts it to a formatted string representation, using the strftime()
function.
Measuring the Execution Time of a Code Block
import time
start_time = time.time()
# code to measure execution time for
for i in range(1000000):
pass
end_time = time.time()
elapsed_time = end_time - start_time
print(f"Elapsed time: {elapsed_time} seconds")
This code uses the time
module to measure the amount of time it takes to execute a code block, and then prints out the elapsed time in seconds. Note that this example uses a simple loop for demonstration purposes - in practice, you would want to measure the execution time of more complex code.
These are just a few examples of the functionality offered by the time
module. You can find more information and examples in the official Python documentation.