Open In App

Python Program to Convert Time from 12 hour to 24 hour Format

Last Updated : 30 Oct, 2025
Comments
Improve
Suggest changes
16 Likes
Like
Report

Given a time in 12-hour AM/PM format, the task is to convert it to military (24-hour) time. For Example:

Input: 11:21:30 PM
Output: 23:21:30

Let’s explore different methods to achieve this conversion.

Using DateTime

This method uses Python's datetime module, which automatically handles the conversion and validates the time format. It is the most reliable and concise approach.

Python
from datetime import datetime

t1 = datetime.strptime('11:21:30 PM', '%I:%M:%S %p')
print(t1.strftime('%H:%M:%S'))

t2 = datetime.strptime('12:12:20 AM', '%I:%M:%S %p')
print(t2.strftime('%H:%M:%S'))

Output
23:21:30
00:12:20

Explanation:

  • datetime.strptime(time, '%I:%M:%S %p') parses the 12-hour format string (%I) and AM/PM (%p) into a datetime object.
  • strftime('%H:%M:%S') converts it into a 24-hour formatted string.

Using Slicing and Conditional Logic

This method directly manipulates the string. It’s simple for well-formatted inputs but requires careful handling of edge cases (12 AM/PM).

Python
t = "08:05:45 PM"

if t[-2:] == "AM" and t[:2] == "12":
    c = "00" + t[2:-2]
elif t[-2:] == "AM":
    c = t[:-2]
elif t[-2:] == "PM" and t[:2] == "12":
    c = t[:-2]
else:
    c = str(int(t[:2]) + 12) + t[2:8]

print(c)

Output
20:05:45

Explanation:

  • Checks the AM/PM suffix (t[-2:]) and the hour part (t[:2]).
  • Adds 12 for PM times except when hour is 12.
  • Removes AM/PM from the final string.

Using Regular Expressions

This method uses regex to extract hour, minute, second, and AM/PM parts, then applies arithmetic logic to convert to 24-hour format.

Python
import re

t = '11:21:30 PM'
hour, mins, sec, am_pm = re.findall(r'\d+|\w+', t)
hour = int(hour)

if am_pm == 'PM' and hour != 12:
    hour += 12
elif am_pm == 'AM' and hour == 12:
    hour = 0

c = f'{hour:02d}:{mins}:{sec}'
print(c)

t2 = '12:12:20 AM'
hour, mins, sec, am_pm = re.findall(r'\d+|\w+', t2)
hour = int(hour)

if am_pm == 'PM' and hour != 12:
    hour += 12
elif am_pm == 'AM' and hour == 12:
    hour = 0

c2 = f'{hour:02d}:{mins}:{sec}'
print(c2)

Output
23:21:30
00:12:20

Explanation:

  • re.findall('\d+|\w+', t) extracts hours, minutes, seconds, and AM/PM.
  • Conditional logic converts the hour to 24-hour format.
  • Formatted using f-string with zero-padding ({hour:02d}).

Explore