+ 2

I want convert time of 12 hour format into 24 hour format like example 1: INPUT: 10:00:00AM OUTPUT: 10:00:00 EXAMPLE. 2: INPUT: 2:00:05PM OUTPUT: 14:00:05

1st Sep 2016, 3:16 AM
AKHILESH VVN
AKHILESH VVN - avatar
3 Réponses
+ 2
The problem of Abjuratio's code that it doesn't do what it expected. It should convert 12:00:00AM to 00:00:00 but it doesn't. It converts 12:00:00PM to 24:00:00AM. And so on.
2nd Sep 2016, 4:54 AM
Textobot
Textobot - avatar
0
import re time12 = input("INPUT 12H <HH:MM:SS(AM|PM)>: ") if re.match(r"^(0[1-9])|(1[0-2])(:[0-5][0-9]){2}(A|P)M
quot;, time12): # (:[0-5][0-9]){2} - for minutes and seconds and colon hours = int(time12[0:2]) # saving hours as int if re.search(r"PM",time12) and hours != 12: # for all PM-cases but 12:mm:ssPM, adding 12 to hours time24 = str(hours+12) + time12[2:-2] elif re.search(r"AM",time12) and hours == 12: # replacing 12 with 00 for 12:mm:ssAM cases time24 = str(0)*2 + time12[2:-2] else: # all the rest just removing AM/PM suffix without change time24 = time12[:-2] print("OUTPUT 24H: " + time24) else: print("Wrong input string format, try again")
1st Sep 2016, 2:36 PM
Textobot
Textobot - avatar
0
I do not understand why to use regular expressions if the input data format is known. Too much code, you can make it easier. def format_time(time): if 'PM' in time: time = time.split(':') time[0] = str(int(time[0]) + 12) time = ":".join(time) time = time.replace("PM", "AM") return (time) print(format_time('10:00:00AM')) print(format_time('02:00:00PM'))
1st Sep 2016, 3:57 PM
Abjuratio Abaeterno
Abjuratio Abaeterno - avatar