Skip to Content

How To Format Time In 24-Hours Using Python (Examples)

How To Format Time In 24-Hours Using Python (Examples)

How do you format time to be in 24-hours using Python?

Date & Time in Python (Differen...
Date & Time in Python (Different Date Formats) (Video 54)

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:

>>> from datetime import datetime
>>> d = "2022-08-31 1:30PM"
>>> datetime.strptime(d, "%Y-%m-%d %I:%M%p")
datetime.datetime(2022, 8, 31, 13, 30)

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:

>>> from datetime import datetime
>>> d = "2022-08-31 1:30PM"
>>> t = datetime.strptime(d, "%Y-%m-%d %I:%M%p")
>>> f"{t:%H%M}"
'13:30'

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.