Python is known for its readability and flexibility, making it a great choice for novice and experienced programmers alike. One of Python’s many functions is its ability to check the current time and date.
This ability makes Python valuable in a multitude of areas, such as creating timestamps or scheduling tasks. This tutorial will guide you through the process of checking the time using Python.
Step 1: Import the datetime module
In Python, it’s necessary to import the library you want to use before performing any operation. Since we want to check the time, we’re going to use the datetime module which is a part of Python’s standard library. Here is how to import it:
1 |
import datetime |
Step 2: Retrieve the current date and time
Python’s datetime module has different methods to get the current date and time. One of those is datetime.now().
1 2 |
current_time = datetime.datetime.now() print(current_time) |
This will output the current date and time in the format:
1 |
YYYY-MM-DD HH:MM:SS.ssssss |
Step 3: Format the date and time output
If you want to format the output to show only the time, you can use the strftime() function. This function formats date and time into string data. For example, if we want to output the time in the format of hours, minutes and seconds, we can use the following code:
1 2 |
formatted_time = current_time.strftime("%H:%M:%S") print(formatted_time) |
The output will be:
1 |
HH:MM:SS |
Here, “%H” represents hour, “%M” represents minute, and “%S” represents second.
The Full Python Code
Here is the full Python code for checking the time:
1 2 3 4 5 6 7 8 9 10 11 |
import datetime # get current date and time current_time = datetime.datetime.now() # print current date time print(current_time) #format and print date to show only time formatted_time = current_time.strftime("%H:%M:%S") print(formatted_time) |
Conclusion
Checking the time in Python is straightforward and effective. The datetime module offers a host of features beyond simply checking the current time, such as manipulating dates and times, formatting, and setting timezones. For any time-related operation in Python, the datetime module is your friend.