Signup/Sign In

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

The 24-hour clock is a timekeeping system in which the day is divided into 24 hours and runs from midnight to midnight.

In this tutorial, we will perform a program to convert the time from 12 hours to 24 hours format.

The Input-output console will look like this:

24hr

Approach

The 24-hour clock is used by the majority of countries. It is 12:00 twice a day, at midnight (AM) and noon (PM), under the 12-hour clock system (PM).

We may need to change the time from 12-hour to 24-hour format throughout the development process.

The program is going to be simple: midnight on a 12-hour clock is 12:00:00 AM and 00:00:00 on a 24-hour clock, and noon is 12:00:00 PM on a 12-hour clock and 12:00:00 on a 24-hour clock.

  1. First, we used datetime as input and retrieved the single time.
  2. Then we examined the remaining two components to determine if they were PM.
  3. then simply add 12 to them and if AM, then don't add
  4. remove AM/PM

Algorithm

As of now we are familiar with the approach of the program now let us have a look at the algorithm followed by the code for a better understanding:

  1. define convert() function
  2. Pass string as a parameter
  3. Check the last two elements of the time
  4. If it is AM and 12 don't add
  5. If it is PM convert it
  6. Remove PM and add 12 to it.
  7. Print the time in desirable format

Python Program

Let's now dive deep into the programming part and the output is given below:

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))


12-hour Format time:: 01:58:42PM
24-hour Format time :: 13:58:42

Conclusion

In this tutorial, we have converted the 12-hour time format to a 24-hour time format using the python programming language. The program is very simple: midnight on a 12-hour clock is 12:00:00 AM and 00:00:00 on a 24-hour clock, and noon is 12:00:00 PM on a 12-hour clock and 12:00:00 on a 24-hour clock. We have followed this approach to get the desired output.



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.