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.
Assume the user inputs a time like 1530
(which means 3:30 PM).
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)
Standard Time: 03:30 PM
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
%H%M
for 24-hour time parsing, and %I:%M %p
for 12-hour formatting (with AM/PM).
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: