How to Convert Time to 24 Hour Format in Python?

Estimated read time 2 min read

To convert time to a 24-hour format in Python, you can use the strftime() method from the datetime module. The strftime() method allows you to format a datetime object into a string representation using specified format codes. Here’s an example of converting time to a 24-hour format:

from datetime import datetime

def convert_to_24_hour_format(time_str):
    # Convert string to datetime object
    time_obj = datetime.strptime(time_str, "%I:%M:%S %p")

    # Convert datetime object to 24-hour format string
    time_24_hour = time_obj.strftime("%H:%M:%S")
    return time_24_hour

In this example, the convert_to_24_hour_format() function takes a time string as input. It uses datetime.strptime() to convert the time string to a datetime object. The %I:%M:%S %p format code is used to match the time string in 12-hour format with AM/PM.

Next, the function uses strftime() on the datetime object to convert it to a string in 24-hour format. The %H:%M:%S format code is used to represent the time in 24-hour format.

You can then call the function and provide the time string as an argument to convert it to 24-hour format:

time_str = "05:30:45 PM"
converted_time = convert_to_24_hour_format(time_str)

This will output:


In this example, the time string “05:30:45 PM” is converted to 24-hour format, resulting in the string “17:30:45”.

Note that the input time string must be in a valid 12-hour format with AM/PM, and the function assumes a valid input format. If the input format is not correct, it may raise a ValueError. Make sure to adjust the input and format codes as per your specific requirements.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply