PUBLISHED ON: AUGUST 25, 2021
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:
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.
- First, we used datetime as input and retrieved the single time.
- Then we examined the remaining two components to determine if they were PM.
- then simply add 12 to them and if AM, then don't add
- 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:
- define convert() function
- Pass string as a parameter
- Check the last two elements of the time
- If it is AM and 12 don't add
- If it is PM convert it
- Remove PM and add 12 to it.
- 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.