In Python, it’s common to work with dates and time, but sometimes we only need to display or work with the time part of a DateTime object. In this tutorial, we will go through how to print only the time in Python using the strftime method from the datetime module.
Step 1: Import the datetime module
First, we need to import the datetime module to work with the date and time. To do this, add the following line in your Python script:
1 |
import datetime |
Step 2: Get the current time
After importing the datetime module, we can get the current date and time using the datetime.now() method, which returns the current date and time as a datetime object.
1 2 |
current_time = datetime.datetime.now() print(current_time) |
2022-08-20 16:32:07.258007
As you can see, the output shows both the date and time.
Step 3: Print only the time using strftime
Now that we have a datetime object with the current date and time, let’s print only the time using the strftime method.
The strftime method allows us to format the date and time in a way that we desire. For displaying only the time, we use the following format codes:
- %H: Hour (24-hour clock) as a decimal number [00,23]
- %M: Minute as a decimal number [00,59]
- %S: Second as a decimal number [00,59]
Update the code as follows:
1 2 |
time_only = current_time.strftime("%H:%M:%S") print("Current time:", time_only) |
Current time: 16:32:07
Now, the output shows only the time part of the datetime object.
Step 4 (optional): Print time with AM/PM
If you want to display the time in a 12-hour format with AM/PM, add the %p format code, which shows either AM or PM based on the time.
Use the following format codes:
– %I: Hour (12-hour clock) as decimal number [01,12]
Update the code as follows:
1 2 |
time_12_hour = current_time.strftime("%I:%M:%S %p") print("Current time (12-hour format):", time_12_hour) |
Current time (12-hour format): 04:32:07 PM
Now, the output shows the time in a 12-hour format with AM/PM.
Full code
1 2 3 4 5 6 7 8 9 10 |
import datetime current_time = datetime.datetime.now() print(current_time) time_only = current_time.strftime("%H:%M:%S") print("Current time:", time_only) time_12_hour = current_time.strftime("%I:%M:%S %p") print("Current time (12-hour format):", time_12_hour) |
2022-08-20 16:32:07.258007 Current time: 16:32:07 Current time (12-hour format): 04:32:07 PM
Conclusion
In this tutorial, we covered how to print only the time in Python using the strftime method from the datetime module. You can easily customize your time display format by combining different format codes. To learn more about the various format codes available, visit the Python datetime documentation.