Program to convert hour minutes’ time to text format in Python

PythonServer Side ProgrammingProgramming

Suppose we have two inputs hour and minutes. We have to show the time in text format. This is like −

  • 8:00 : 8'o clock
  • 8:01 : one minute past eight
  • 8:10 : ten minutes past eight
  • 8:15 : quarter past eight
  • 8:30 : half past eight
  • 8:40 : twenty minutes to nine
  • 8:45 : quarter to nine
  • 8:47 : thirteen minutes to nine
  • 8:28 : twenty eight minutes past eight

So, if the input is like h = 9, m = 42, then the output will be eighteen minutes to ten

To solve this, we will follow these steps −

  • text:= a list containing texts for 30 different numeric values as follows: ["one", "two", "three", "four", "five", "six", "seven", "eight","nine","ten", "eleven", "twelve", "thirteen", "fourteen", "quarter", "sixteen","seventeen", "eighteen", "nineteen", "twenty", "twenty-one","twenty-two", "twenty-three", "twenty-four", "twenty-five","twenty-six", "twenty-seven", "twenty-eight", "twenty-nine", "half"]
  • op:= blank string
  • if m is same as 0, then
    • op := text[h - 1] concatenate " o' clock"
  • otherwise when m is same as 30, then
    • op := text[m - 1] concatenate " past " concatenate text[h - 1]
  • otherwise when m is same as 1, then
    • op := text[m - 1] concatenate " minute past " concatenate text[h - 1]
  • otherwise when m is same as 15, then
    • op := text[m - 1] concatenate " past " concatenate text[h - 1]
  • otherwise when m − 30 is non-zero, then
    • op := text[m - 1] concatenate " minutes past " concatenate text[h - 1]
  • otherwise when m is same as 45, then
    • op := "quarter to " concatenate text[h]
  • otherwise
    • op := text[(60 - m) -1] concatenate " minutes to " concatenate text[h]
  • return op

Example

Let us see the following implementation to get better understanding −

def solve(h, m):
   text=["one", "two", "three", "four", "five", "six", "seven", "eight","nine","ten", "eleven", "twelve", "thirteen", "fourteen", "quarter", "sixteen","seventeen", "eighteen", "nineteen", "twenty", "twenty-one","twenty-two", "twenty-three", "twenty-four", "twentyfive"," twenty-six", "twenty-seven", "twenty-eight", "twenty-nine", "half"]

   op=""
   if (m == 0):
      op = text[h - 1] + " o' clock"
   elif (m == 30):
      op = text[m - 1]+ " past " + text[h - 1]
   elif (m == 1):
      op = text[m - 1] + " minute past " + text[h - 1]
   elif (m == 15):
      op = text[m - 1]+ " past " + text[h - 1]
   elif (m < 30):
      op = text[m - 1] + " minutes past " + text[h - 1]
   elif (m==45):
      op = "quarter to " + text[h]
   else:
      op = text[(60 - m)-1] + " minutes to " + text[h]
   return op

h = 9
m = 42
print(solve(h, m))

Input

9, 42

Output

eighteen minutes to ten
raja
Published on 07-Oct-2021 12:42:35
Advertisements