Python program to convert time from 12 hour to 24 hour format
The 24-hour clock is the convention of time keeping where the day runs from midnight to midnight and is divided into 24 hours. Most countries prefer the 24 hour clock method. In the 12 hour clock method, it is 12:00 twice a day at midnight (AM) and noon (PM). In the development process, we may need to convert time from 12 hour to 24 hour format. The logic is very simple, the midnight is 12:00:00 AM on a 12-hour clock and 00:00:00 on a 24-hour clock and the noon is 12:00:00 PM on the 12-hour clock and 12:00:00 on the 24-hour clock.
ExampleInput : 11:14:22 PM
Output : 23:14:22
Input : 12:03:21 AM
Output : 00:03:21
Here is the program to convert time from 12 hour to 24 hour format. First, we have taken datetime as input and extracted the only time from datetime format. Next, we checked if last two elements are PM, then simply add 12 to them and if AM, then don't add and remove AM/PM -
def convert12to24hour(str1):
# checking last two elements of time
# if it is AM and first two elements are 12
if str1[-2:] == "AM" and str1[:2] == "12":
return "00" + str1[2:-2]
# remove the AM
elif str1[-2:] == "AM":
return str1[:-2]
# If last two elements of time is PM
# and first two elements are 12
elif str1[-2:] == "PM" and str1[:2] == "12":
return str1[:-2]
else:
# remove PM and add 12 to hours
return str(int(str1[:2]) + 12) + str1[2:8]
print("Time ::",convert12to24hour("02:05:45 PM"))
Output of the above code -
Time :: 14:05:45
Related Articles
Convert list to dictionary Python
Convert array to list Python
numpy dot product
glob in Python
Python heap implementation
zip function in Python
Remove last element from list Python
Check if list is empty Python
Remove element from list Python
Python split multiple delimiters
Python loop through list
Python iterate list with index
Python add list to list
Python random choice
Python dict inside list
Remove character from string Python
Python raise keyword