94.7k views
3 votes
Write a program that inputs a time from the console. The time should be in the format "HH:MM AM" or "HH:MM PM". Hours may be one or two digits, for example, "1:10 AM" or "11:30 PM". Your program should include a function that takes a string parameter containing the time. This function should convert the time into a four-digit military time based on a 24-hour clock. For example, "1:10 AM" would output "0110 hours", "11:30 PM" would output "2330 hours", and "12:15 AM" would output "0015 hours". The function should return a string to main for writing it out to the console. (Do not output the value in the function.) Sample runs of the program:

1 Answer

4 votes

Answer:

  1. def processTime(timeStr):
  2. timeData = timeStr.split(" ")
  3. timeComp = timeData[0].split(":")
  4. h = int(timeComp[0])
  5. m = int(timeComp[1])
  6. output = ""
  7. if(timeData[1] == "AM"):
  8. if(h < 10):
  9. output += "0" + str(h) + str(m) + " hours"
  10. elif(h == 12):
  11. output += "00" + str(m) + " hours"
  12. else:
  13. output += str(h) + str(m) + " hours"
  14. else:
  15. h = h + 12
  16. output += str(h) + str(m) + " hours"
  17. return output
  18. print(processTime("11:30 PM"))

Step-by-step 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

User Max Go
by
4.5k points