Military Time

wordcloud

Note: This page contains a small but interesting piece of Python code which I call snippets. You can find more such codes on my Python snippets page.

Problem

You want to convert the time from a 12 hour clock to a 24 hour clock. If you are given the time on a 12 hour clock, you should output the time as it would appear on a 24 hour clock.

Task:
Determine if the time you are given is AM or PM, then convert that value to the way that it would appear on a 24 hour clock.

Input Format:
A string that includes the time, then a space and the indicator for AM or PM.

Output Format:
A string that includes the time in a 24 hour format (XX:XX)

Sample Input:
1:15 PM

Sample Output:
13:15

Solution

Here is my solution to the above problem. Remember that there could be more than one way to solve a problem. If you have a more efficient or concise solution, please leave a comment.

In [1]:
t=input()
hhmm=[int(x) for x in t[:len(t)-3].split(":")]
if t[len(t)-2:]=="PM": hhmm[0]+=12
print(":".join(["{:02d}".format(x) for x in hhmm]))
02:05

Explanation

My approach (or the algorithm)

  1. Extract hour, minute and AM/PM from the input.
  2. If PM, then add 12 to hour.
  3. Convert hour and minute to HH:MM format.

The code

  • t[:len(t)-3] is the numeric part of the input containing hour and minute data without AM/PM.
  • split(":") splits the above hour/minute data into a list [hour, minute]
  • [int(x) for x in t[:len(t)-3].split(":")] converts the elements of the above list into integers. The hour/minute data can now be manipulated as integers.
  • t[len(t)-2:] is the AM/PM part of the input.
  • If PM, then 12 is added to hour data hhmm[0]+=12
  • "{:02d}".format(x) hour/minute elements of the list are converted to 2-digit format.
  • and joined with a colon ":".join

The problem question is picked from SoloLearn. Here is my SoloLearn code and my SoloLearn profile page.

Last updated 2021-01-09 14:38:13.584558 IST

Comments