Convert 12-Hour AM/PM Time to 24-Hour Military Time

Quick Overview

Convert a time string in 12-hour AM/PM format such as 07:05:45PM into 24-hour military time. Tests careful string parsing, the midnight and noon edge cases around hour 12, and zero-padded output formatting.

Convert 12-Hour AM/PM Time to 24-Hour Military Time

Company: Sap

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

Given a time in 12-hour AM/PM format, convert it to military (24-hour) time. The input is a string `s` in the format `hh:mm:ssAM` or `hh:mm:ssPM`. Return the converted time as a string in the format `hh:mm:ss` using 24-hour notation. ### Function Signature ```python def time_conversion(s: str) -> str: ``` ### Rules - `12:00:00AM` on a 12-hour clock is `00:00:00` on a 24-hour clock (midnight). - `12:00:00PM` on a 12-hour clock is `12:00:00` on a 24-hour clock (noon). - The output hour is zero-padded to two digits. Minutes and seconds are the same as in the input. ### Constraints - The input time string is in the format `hh:mm:ssAM` or `hh:mm:ssPM`. - `1 <= hh <= 12` - `00 <= mm <= 59` - `00 <= ss <= 59` ### Examples ```text Input: s = "07:05:45PM" Output: "19:05:45" ``` 7 PM is hour 19 on a 24-hour clock (7 + 12). Minutes and seconds carry over unchanged. ```text Input: s = "12:00:00AM" Output: "00:00:00" ``` 12 AM is midnight, which is hour 00 on a 24-hour clock. ```text Input: s = "12:45:54PM" Output: "12:45:54" ``` 12 PM is the noon hour, which stays 12. Adding 12 here would produce the invalid hour 24.

Overview: Convert a time string in 12-hour AM/PM format such as 07:05:45PM into 24-hour military time. Tests careful string parsing, the midnight and noon edge cases around hour 12, and zero-padded output formatting.

Sap logo
Sap
Nov 24, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Given a time in 12-hour AM/PM format, convert it to military (24-hour) time.

The input is a string s in the format hh:mm:ssAM or hh:mm:ssPM. Return the converted time as a string in the format hh:mm:ss using 24-hour notation.

Function Signature

def time_conversion(s: str) -> str:

Rules

  • 12:00:00AM on a 12-hour clock is 00:00:00 on a 24-hour clock (midnight).
  • 12:00:00PM on a 12-hour clock is 12:00:00 on a 24-hour clock (noon).
  • The output hour is zero-padded to two digits. Minutes and seconds are the same as in the input.

Constraints

  • The input time string is in the format hh:mm:ssAM or hh:mm:ssPM .
  • 1 <= hh <= 12
  • 00 <= mm <= 59
  • 00 <= ss <= 59

Examples

Input: s = "07:05:45PM"
Output: "19:05:45"

7 PM is hour 19 on a 24-hour clock (7 + 12). Minutes and seconds carry over unchanged.

Input: s = "12:00:00AM"
Output: "00:00:00"

12 AM is midnight, which is hour 00 on a 24-hour clock.

Input: s = "12:45:54PM"
Output: "12:45:54"

12 PM is the noon hour, which stays 12. Adding 12 here would produce the invalid hour 24.