+ 3

Military Time challenge

How to do It better? time=input().split() f_time=time[0].split(":") f_time.append(time[1]) #f_time=['HH','MM','mode'] hour=f_time[0] minutes=f_time[1] mode=f_time[2] def pm(): global hour pm_hour=int(hour)+12 hour=str(pm_hour) return hour if mode=="PM": pm() print("{}:{}".format(hour,minutes)) https://code.sololearn.com/c0M0p3Vv7Sj2/?ref=app

15th Mar 2022, 7:46 PM
David Ortega
David Ortega - avatar
12 Antworten
+ 2
m = input() s = m.strip().replace(" ", ":").split(":") if s[2] == "PM": if s[0]=="12": print(f'12:{s[1]:0>2}') else: print(f'{int(s[0])+12}:{s[1]:0>2}') else: if s[0]=="12": print(f'00:{s[1]:0>2}') else: print(f'{s[0]:0>2}:{s[1]:0>2}') https://code.sololearn.com/ce9A91TBq7WF https://en.wikipedia.org/wiki/24-hour_clock Keep learning & happy coding :D
15th Mar 2022, 8:09 PM
SoloProg
SoloProg - avatar
+ 2
m = input() s = m.strip().replace(" ", ":").split(":") This part is what I need, thanks!!!
15th Mar 2022, 8:20 PM
David Ortega
David Ortega - avatar
+ 2
david ortega the code fails if you enter any time in the 12 o'clock hour. 12:30 AM -> 12:30 (should be 00:30) 12:30 PM -> 24:30 (should be 12:30) For reference, here is my 3-line solution. #input format is hh:mm <A|P>M #mm_M is both, minutes and Meridian hr, mm_M = input().split(':', 1) #12 AM is 00. For PM hours add 12. hr = int(hr)%12 + 12*(mm_M[-2]=='P') #{hr:02} #2-digit hour with filler 0 #mm_M[:2] #minutes without meridian print(f"{hr:02}:{mm_M[:2]}")
15th Mar 2022, 8:31 PM
Brian
Brian - avatar
+ 2
Yeah, Sololearn's test cases were not written by an experienced tester.
15th Mar 2022, 8:38 PM
Brian
Brian - avatar
15th Mar 2022, 8:55 PM
SoloProg
SoloProg - avatar
+ 2
Using ternary operator time = input().replace(":"," ").split() if time[2] =="AM": mt = "00" if time[0] =="12" else time[0] else: mt = int(time[0])+12 if time[0] != "12 else "12" print(f"{mt}:{time[1]}")
16th Mar 2022, 9:48 AM
Simba
Simba - avatar
+ 1
It's true! Military Time challenge's bug?
15th Mar 2022, 8:36 PM
David Ortega
David Ortega - avatar
+ 1
Upvote if you like my code :)
15th Mar 2022, 8:43 PM
SoloProg
SoloProg - avatar
+ 1
if mode=="PM" and int(hour)<12: pm() This solve the problem. I think 12:30 AM is not a valid entry, doesn't exist that hour.
15th Mar 2022, 8:48 PM
David Ortega
David Ortega - avatar
+ 1
12:30 AM is a valid time in the US. Is it not in Europe?
15th Mar 2022, 8:58 PM
Brian
Brian - avatar
0
As I understand 12:30 is always post meridian, also 12:30 AM must be 00:30
15th Mar 2022, 9:30 PM
David Ortega
David Ortega - avatar
0
This cultural difference is new to me. Just mentioning 12:30 here leaves it open to interpretation whether it means AM or PM, but rarely does anyone use 00:30 here, which would solve the issue!
15th Mar 2022, 9:56 PM
Brian
Brian - avatar