Learnitweb

Python program to convert time from 12 hour to 24 hour format

Approach 1: Using slicing

Whether the input time is in 12 hour format or not can be checked by checking the last two elements. If the last two elements are AM or PM then the input time is in 12 hour format.
If PM, add 12 to the time. If AM, then don’t add.

# Python program to convert time from 12 hour to 24 hour format

def convertTo24HourFormat(inputTime):
     
    # Check if last two elements of time is AM and first two elements are 12
    if inputTime[-2:] == "AM" and inputTime[:2] == "12":
        return "00" + inputTime[2:-2]
         
    # remove the AM from input   
    elif inputTime[-2:] == "AM":
        return inputTime[:-2]
     
    # Check if last two elements of time is PM and first two elements are 12   
    elif inputTime[-2:] == "PM" and inputTime[:2] == "12":
        return inputTime[:-2]
         
    else:
        # Add 12 to hours and remove PM
        return str(int(inputTime[:2]) + 12) + inputTime[2:8]
 
# Driver Code - to call function with input data        
print("10:09:30 AM in 24 hour format is: ", convertTo24HourFormat("10:09:30 AM"))
print("07:30:15 PM in 24 hour format is: ", convertTo24HourFormat("07:30:15 PM"))

Output

10:09:30 AM in 24 hour format is:  10:09:30
07:30:15 PM in 24 hour format is:  19:30:15

Approach 2: using strftime() and strptime()

  • strftime(format) method creates a string representing the time based on a format string.
  • strptime() class method creates a datetime object from a string representing a date and time based on a format string.

There are various directives used in a format string. We’ll use the following directives:

DirectiveMeaningExample
%IHour (12-hour clock) as a zero-padded decimal number.01, 02, …, 12
%MMinute as a zero-padded decimal number.00, 01, …, 59
%pLocale’s equivalent of either AM or PM. AM, PM (en_US)
%HHour (24-hour clock) as a zero-padded decimal number.00, 01, …, 23
%MMinute as a zero-padded decimal number.00, 01, …, 59
%SSecond as a zero-padded decimal number.00, 01, …, 59
#import datetime
from datetime import datetime

#sample input time to be converted
inputTime = '03:20:19 PM'

#Create datetime object from string
in_time = datetime.strptime(inputTime, "%I:%M:%S %p")

#convert to 24 hour format
out_time = datetime.strftime(in_time, "%H:%M:%S")

#print result
print(out_time)

Output

15:20:19