Convert 12 hour to 24 hour time format in Python

Given a time in 12-hour AM/PM format, convert it to military (24-hour) time. Note : Midnight is 12:00:00 AM on a 12-hour clock and 00:00:00 on a 24-hour clock. Noon is 12:00:00 PM on 12-hour clock and 12:00:00 on 24-hour clock.

Examples :

Input : 11:21:30 PM
Output : 23:21:30

Input : 12:12:20 AM
Output : 00:12:20

How to Convert AM/PM to 24 Hour Time

Whether the time format is 12 hours or not, can be found out by using list slicing. Check if last two elements are PM, then simply add 12 to them. If AM, then don’t add. Remove AM/PM from the updated time.

def convert(string):

      if string[-2:] == "AM" and string[:2] == "12":
         return "00" + string[2:-2]

      elif string[-2:] == "AM":
         return string[:-2]

      elif string[-2:] == "PM" and string[:2] == "12":
         return string[:-2]
        
      else:
          return str(int(string[:2]) + 12) + string[2:8]

#driver code
time="01:58:42PM"
print("12-hour Format time:: ", time)
print("24-hour Format time ::",convert(time))
OUTPUT:
12-hour Format time:: 01:58:42PM
24-hour Format time :: 13:58:42v

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top