Program to convert time from 12 hour format to 24 hour format in Python

by | Jun 3, 2021 | Python Programs

Introduction

The task is to convert the given time in 12 hour format (AM/PM) into 24 hour format.

Program to convert time from 12 hour format to 24 hour format in Python

Program

def convert(time):
    if time[-2:] == "AM" and time[:2] == "12":
        return "00" + time[2:-2]
    elif time[-2:] == "AM":
        return time[:-2]
    elif time[-2:] == "PM" and time[:2] == "12":
        return time[:-2]
    else:
        return str(int(time[:2])+12 ) + time[2:8]


twelve_hr = ("09:00:16 PM")
print("The provided time in 12 hour format is: ", twelve_hr)
print("The converted time in 24 hour format is: ", convert(twelve_hr))

 

Output:

Program to convert time from 12 hour format to 24 hour format in Python Output

Explanation

In the above code we have checked whether the given time is AM or PM. If the time is in PM, we have added 12 to the given time, removed the PM from it and return the time. If the time is in AM, we have just removed the AM from it and returned it.

Author

0 Comments

Submit a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.