How to Convert 24 Hours to 12 Hours in Python?

Estimated read time 1 min read

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

from datetime import datetime

def convert_to_12_hour_format(time_24h):
    # Parse the time string in 24-hour format
    time_24h_obj = datetime.strptime(time_24h, "%H:%M")

    # Convert the time to 12-hour format
    time_12h = time_24h_obj.strftime("%I:%M %p")

    return time_12h

# Example usage
time_24h = "14:30"
time_12h = convert_to_12_hour_format(time_24h)
print(time_12h)

In this code, the convert_to_12_hour_format function takes a time string in 24-hour format (e.g., “14:30”) as input. It uses the strptime method from the datetime module to parse the time string into a datetime object.

Then, it uses the strftime method to format the datetime object back into a string representation in 12-hour format (“%I:%M %p”). The %I represents the hour in 12-hour format, %M represents the minute, and %p represents “AM” or “PM”.

Finally, the function returns the time string in 12-hour format.

In the example usage, we convert the time “14:30” to 12-hour format and print the result, which would be “02:30 PM”.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply