How to Convert Military Time to Standard Time in Python

Military time (24-hour format) ranges from 0000 to 2359. Python makes it easy to convert this into standard 12-hour format using the datetime module.

Step 1: Accept Military Time as Input

Assume the user inputs a time like 1530 (which means 3:30 PM).

Step 2: Use Python's datetime Module

from datetime import datetime

military_time = "1530"

# Convert string to datetime object
dt_object = datetime.strptime(military_time, "%H%M")

# Format into 12-hour standard time
standard_time = dt_object.strftime("%I:%M %p")

print("Standard Time:", standard_time)

Output:

Standard Time: 03:30 PM

Step 3: Add Input Validation

Always validate the input to avoid crashes with bad values:

def convert_military_to_standard(time_str):
    try:
        dt = datetime.strptime(time_str, "%H%M")
        return dt.strftime("%I:%M %p")
    except ValueError:
        return "Invalid time format. Use 4-digit 24-hour format like '0930'."

# Example usage
print(convert_military_to_standard("2415"))  # Invalid
print(convert_military_to_standard("0815"))  # Valid
Tip: Use %H%M for 24-hour time parsing, and %I:%M %p for 12-hour formatting (with AM/PM).

Why Use datetime?

Python’s datetime module is built to handle time safely and cleanly—perfect for converting, formatting, and calculating time in any format.


Summary: With just a few lines of code, you can convert military time to standard time in Python. It’s fast, readable, and reliable—great for anything from scheduling apps to command-line tools.

Related pages: