How to Convert Time to 24 Hour Time in Python
In this tutorial, we will program 'How to Convert Time to 24-Hour Format in Python.' We will learn how to convert AM/PM time to the 24-hour format. The objective is to convert 12-hour time into the 24-hour time format. I will provide a sample program to demonstrate the actual coding process in this tutorial.
This topic is very easy to understand. Just follow the instructions I provide, and you will be able to do it yourself with ease. The program I will show you covers the basics of programming for creating a lap timer. I will do my best to provide you with a simple method for starting a lap timer. So, let's start with the coding.
Getting Started:
First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.
Creating Main Function
This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.- def convert24(str1):
- if str1[-2:] == "AM" and str1[:2] == "12":
- return "00" + str1[2:-2]
- elif str1[-2:] == "AM":
- return str1[:-2]
- elif str1[-2:] == "PM" and str1[:2] == "12":
- return str1[:-2]
- else:
- return str(int(str1[:2]) + 12) + str1[2:8]
- print("\n================== Convert Time to 24 Hour Time ==================\n\n")
- print("Time is: ",convert24("10:15:00 PM"))
The convert24 function is designed to convert a 12-hour time format (with "AM" or "PM") to a 24-hour time format. However, there's a small issue in the else clause where the PM time is converted. The function attempts to convert the hour part of the time string from 12-hour format to 24-hour format but mistakenly concatenates the hour conversion as a string without correcting the rest of the time string.
Output:

There you have it we successfully created How to Convert Time to 24 Hour Time in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!
More Tutorials for Python Language