How to Convert 12-Hour Time to 24-Hour Time in Python?

Estimated read time 2 min read

To convert a 12-hour time format to a 24-hour time format in Python, you can use the strptime() and strftime() functions from the datetime module. Here’s an example:

from datetime import datetime

def convert_to_24_hour(time_string):
    # Parse the time string as a datetime object
    time_obj = datetime.strptime(time_string, '%I:%M %p')
    
    # Convert the datetime object to a 24-hour time format string
    time_24_hour = time_obj.strftime('%H:%M')
    
    return time_24_hour

# Example usage
time_string = '09:30 PM'
result = convert_to_24_hour(time_string)
print(result)

In this example, we define a function convert_to_24_hour that takes a time string in the 12-hour format as input. The strptime() function is used to parse the time string as a datetime object.

The format specifier %I:%M %p is used to indicate the format of the time string. %I represents the hour in 12-hour format, %M represents the minutes, and %p represents either ‘AM’ or ‘PM’.

Once we have the datetime object, we can use the strftime() function to format it as a 24-hour time string. The format specifier %H:%M is used to indicate the format of the output string, where %H represents the hour in 24-hour format and %M represents the minutes.

Finally, we return the time_24_hour string, which will contain the converted time in the 24-hour format.

In the example, we convert the time string '09:30 PM' to the 24-hour format. You can replace time_string with your own 12-hour time string to convert it to the 24-hour format.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply