In this tutorial, we will cover the time module in Python, which is an essential module for dealing with various time-related functions. Using the time module, you can access various functionalities like the current time, sleep, and format time.
Step 1: Import the time module
To use the time module functionalities in your code, you need to first import it. Here’s how to import the time module.
1 |
import time |
Step 2: Using the time() function to get the current time
The time()
function in the time module returns the current time in seconds since the epoch (January 1, 1970).
Here’s an example of how to get the current time using the time module in Python:
1 2 3 4 |
import time current_time = time.time() print("Current time:", current_time) |
Output:
Current time: 1631206377.575839
Step 3: Using the sleep() function to make your program wait
The sleep()
function in the time module can be used to add a pause to your program. The function takes a single argument in seconds.
Here’s an example of the sleep() function:
1 2 3 4 5 |
import time print("Starting...") time.sleep(3) # Pauses the code execution for 3 seconds print("...End") |
Output:
Starting... (wait for 3 seconds) ...End
Step 4: Using the ctime() function to convert the time to a string
The ctime()
function in the time module takes time in seconds as input and returns a string representing the local time.
Here’s an example of how to use the ctime() function:
1 2 3 4 5 6 7 |
import time current_time = time.time() print("Current time in seconds:", current_time) current_time_string = time.ctime(current_time) print("Current time (string):", current_time_string) |
Output:
Current time in seconds: 1631206377.575839 Current time (string): Thu Sep 9 12:46:17 2021
Full Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import time # Get the current time current_time = time.time() print("Current time:", current_time) # Sleep function print("Starting...") time.sleep(3) print("...End") # Convert time to string current_time_string = time.ctime(current_time) print("Current time (string):", current_time_string) |
Conclusion
In this tutorial, we have learned about the Python time module and its essential functions, such as time()
, sleep()
, and ctime()
. Being familiar with these functions will help you efficiently manage time-related tasks in your Python programs.