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

Question:

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?

Asked By: Kurt Peek

||

Answers:

I figured it out: it was converting “12:00:00PM” to “24:00:00” and not “12:00:00”. I modified the code as follows:

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 = hour % 12 + 12
    print str(hour) + time_without_meridian[2:]

leading to it passing all the test cases (see below).

enter image description here

Answered By: Kurt Peek

You’ve already solved the problem but here’s another possible answer:

from datetime import datetime


def solution(time):
    return datetime.strptime(time, '%I:%M:%S%p').strftime('%H:%M:%S')


if __name__ == '__main__':
    tests = [
        "12:00:00PM",
        "12:00:00AM",
        "07:05:45PM"
    ]
    for t in tests:
        print solution(t)

Although it’d be using a python library 🙂

Answered By: BPL

It’s even simpler than how you have it.

hour = int(time[:2])
meridian = time[8:]
# Special-case '12AM' -> 0, '12PM' -> 12 (not 24)
if (hour == 12):
    hour = 0
if (meridian == 'PM'):
    hour += 12
print("%02d" % hour + time[2:8])
Answered By: selbie
from datetime import datetime

#Note the leading zero in 05 below, which is required for the formats used below

regular_time = input("Enter a regular time in 05:48 PM format: ")

#%I is for regular time. %H is for 24 hr time, aka "military time"
#%p is for AM/PM

military_time = datetime.strptime(regtime, '%I:%M %p').strftime('%H:%M')

print(f"regular time is: {regular_time"}
print(f"militarytime is {military_time}")

The following link proved to be very helpful: https://strftime.org/

Answered By: Troy
dt_m = datetime.datetime.fromtimestamp(m_time)
hour_m = (dt_m.hour%12)+1  #dt_m.hour+1
offset_dt = datetime.datetime(dt_m.year, dt_m.month, dt_m.day, hour_m , dt_m.minute, dt_m.second, dt_m.microsecond)
Answered By: james scott
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.