Kurt Peek Kurt Peek - 3 months ago 12
Python Question

Converting time from AM/PM format to military time in Python

Without using any libraries, I'm trying to solve the Hackerrank problem "Time Conversion", the problem statement of which is copied below.

enter image description here

I came up with the following:

time = raw_input().strip()

meridian = time[-2:] # "AM" or "PM"
time_without_meridian = time[:-2]
hour = int(time[:2])

if meridian == "AM":
hour = (hour+1) % 12 - 1
print ("%02d" % hour) + time_without_meridian[2:]
elif meridian == "PM":
hour += 12
print str(hour) + time_without_meridian[2:]


However, this fails on one test case:

enter image description here

Since the test cases are hidden to the user, however, I'm struggling to see where the problem is occurring. "12:00:00AM" is correctly converted to "00:00:00", and "01:00:00AM" to "01:00:00" (with the padded zero). What could be wrong with this implementation?

Answer

It's even simpler than how you have it.

hour = int(time[:2])
meridian = time[8:]
if (hour == 12):
    hour = 0
if (meridian == 'PM'):
    hour += 12
print("%02d" % hour + time[2:8])
Comments