Python program to convert time from 12 hour to 24 hour format

Created with Sketch.

Python Program to Convert Time from 12-Hour to 24-Hour Format

Introduction

Time representation in 12-hour and 24-hour formats is common in various applications. Converting time from a 12-hour format (AM/PM) to a 24-hour format is a useful task in programming. This Python program demonstrates how to convert time from the 12-hour format to the 24-hour format.

Understanding the Algorithm

The algorithm for converting time from the 12-hour format to the 24-hour format involves the following steps:

  1. Input Time: Accept the time in the 12-hour format (with AM/PM).
  2. Extract Components: Split the input time into hours, minutes, and AM/PM components.
  3. Conversion: Adjust the hours based on the AM/PM component to obtain the equivalent 24-hour format.
  4. Display Result: Print or display the converted time in the 24-hour format.

Python Program for Time Conversion

def convert_12_to_24(time_12hr):
    # Split the input time into hours, minutes, and AM/PM components
    time_components = time_12hr.split(":")
    hours, minutes = map(int, time_components[:-1])
    am_pm = time_components[-1].upper()

    # Convert 12-hour format to 24-hour format
    if am_pm == "PM" and hours != 12:
        hours += 12
    elif am_pm == "AM" and hours == 12:
        hours = 0

    # Format the result in 24-hour format
    time_24hr = f"{hours:02d}:{minutes:02d}"

    return time_24hr

# Example: Convert 12-hour time to 24-hour format
time_12hr_example = "03:30 PM"
converted_time = convert_12_to_24(time_12hr_example)

# Display the result
print(f"Converted Time (12-hour to 24-hour): {converted_time}")

Output Example

Example: Convert 12-hour Time to 24-hour Format

Converted Time (12-hour to 24-hour): 15:30

Explanation

The Python program defines a function convert_12_to_24 that takes a time string in the 12-hour format as input. The function extracts hours, minutes, and AM/PM components, performs the conversion, and returns the time in the 24-hour format.

The example provided demonstrates how to convert the 12-hour time “03:30 PM” to the equivalent 24-hour format.

Conclusion

Converting time between different formats is a common requirement in programming, especially in applications dealing with time-sensitive data. This Python program showcases a simple yet effective algorithm for converting time from the 12-hour format to the 24-hour format. Feel free to experiment with different time inputs to explore the conversion process.

If you have any questions or need further clarification, please don’t hesitate to ask!

Leave a Reply

Your email address will not be published. Required fields are marked *