Time Conversion from 12-hour to 24-hour format in Python

In this tutorial, given time in 12-hour format as input we will learn how to perform time conversion into the 24-hour format and output it using Python.

Time Conversion in Python

Given time in 12-hour AM/PM format, we aim to convert it into the 24-hour(military) format.

Example:

10:40:06AM
10:40:06

10:40:06PM
22:40:06

Also, be mindful of the fact that midnight is at 12:00: 00 AM in 12-hour format and 00:00:00 in 24-hour format, and noon is at 12:00: 00 PM in 12-hour format and 12:00:00 in 24-hour format.

Implementation in Python

First, let us take the input.

time_12 = input().strip()

We use the strip() method to strip off any trailing and leading white spaces.

Let us now check if the given time is in AM or PM.

time_in_pm = time_12[-2:].lower() == 'pm'

If it is in AM then the time_in_pm variable will be holding False and if it is in PM then the time_in_pm variable will be holding True.

time_list = list(map(int, time_12[:-2].split(':')))

Here, we get the hours, minutes and seconds in the given time leaving the AM/PM part of the string.

If the time is in AM and the hours part is 12 then we need to change the hours part to 0. If the hours part is not equal to 12 then we can print the time without any changes.

if not time_in_pm and time_list[0] == 12:
    time_list[0] = 0

If the time is in PM then we need to add 12 to the hours part to convert it into the 24-hour format. If the hours part is equal to 12 then we need not change anything.

if time_in_pm and time_list[0] < 12:
    time_list[0] += 12

Let us now print the time in the 24-hour format.

print(':'.join(map(lambda x: str(x).rjust(2, '0'), time_list)))

Output:

06:30:21AM
06:30:21
06:30:21PM
18:30:21

Also read, Print time in all time zones in Python

Leave a Reply