Without using any libraries, I'm trying to solve the Hackerrank problem "Time Conversion", the problem statement of which is copied below.
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:
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?
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.
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.
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])
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 :-)
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With