How do you format time to be in 24-hours using Python?
In Python you can format a datetime object to be displayed in 24-hour time using the format %H:%M. This is not to be confused with the 12-hour time which uses the format %I:%M and may have %p appended to the end to denote AM/PM.
Here’s an example demonstrating the conversion of time from 12-hour format to a 24-hour format:
| |
As you can see from the above code the original string d contains the year followed by the month and then the day of the month along with the time in 12-hour format. To get Python to interpret this string into a datetime object you instruct Python using the format strings in the second parameter of the datetime.strptime() method.
%Y is the year as a four-digit number, %m is the month as a two-digit number, %d is the day of the month as a two-digit number, %I is the hour in 12-hour time, %M (capital m) is the minute and %p is the AM/PM designation.
As you can see from the result the datetime object outputs the year, month, day, hour in 24-hour time, and minute.
To output this datetime object in 24-hour time you can use an f-string with the format style, like so:
| |
As you can see from the above result the outcome of getting 24-hour time is achieved! The f-string enables the use of styling the string using the format modifier and by using the datetime format tags you can output the hour in 24-hour format with %H and the minute would not change (%M).
Summary
The above explains how to format time in Python to be in 24-hour time instead of 12-hour time. It goes over how to use the format string %H:%M to obtain the desired result from a datetime object in 24-hour time. Additionally, you have seen how to use the f-string format modifier to display the datetime object in 24-hour time.