Answer:
- def processTime(timeStr):
- timeData = timeStr.split(" ")
- timeComp = timeData[0].split(":")
- h = int(timeComp[0])
- m = int(timeComp[1])
-
- output = ""
-
- if(timeData[1] == "AM"):
- if(h < 10):
- output += "0" + str(h) + str(m) + " hours"
- elif(h == 12):
- output += "00" + str(m) + " hours"
- else:
- output += str(h) + str(m) + " hours"
- else:
- h = h + 12
- output += str(h) + str(m) + " hours"
-
- return output
-
- print(processTime("11:30 PM"))
Explanation:
The solution code is written in Python 3.
Firstly, create a function processTime that takes one input timeStr with format "HH:MM AM" or "HH:MM PM".
In the function, use split method and single space " " as separator to divide the input time string into "HH:MM" and "AM" list items (Line 2)
Use split again to divide first list item ("HH:MM") using the ":" as separator into two list items, "HH" and "MM" (Line 3). Set the HH and MM to variable h and m, respectively (Line 4-5)
Next create a output string variable (Line 7)
Create an if condition to check if the second item of timeData list is "AM". If so, check again if the h is smaller than 10, if so, produce the output string by preceding it with a zero and followed with h, m and " hours" (Line 9 - 11). If the h is 12, precede the output string with "00" and followed with h, m and " hours" (Line 12 - 13). Otherwise generate the output string by concatenating the h, m and string " hours" (Line 14 -15)
If the second item of timeData is "PM", add 12 to h and then generate the output string by concatenating the h, m and string " hours" (Line 17 -18)
Test the function (Line 22) and we shall get the sample output like 2330 hours