Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 905
Kurt Peek Avatar asked Aug 27 '16 18:08

Kurt Peek


People also ask

How do I change to 12-hour format in Python?

The key to this code is to use the library function time. strptime() to parse the 24-hour string representations into a time. struct_time object, then use library function time. strftime() to format this struct_time into a string of your desired 12-hour format.

How do you convert time to military time?

To convert from standard time to military time, simply add 12 to the hour. So, if it's 5:30 p.m. standard time, you can add 12 to get the resulting 1730 in military time. To convert from military time to standard time, just subtract 12 from the hour.


3 Answers

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])
like image 60
selbie Avatar answered Sep 22 '22 05:09

selbie


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 :-)

like image 25
BPL Avatar answered Sep 23 '22 05:09

BPL


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/

like image 40
Troy Avatar answered Sep 26 '22 05:09

Troy