Advertisement
acclivity

pyTimePlusDuration

Jul 25th, 2022
1,154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.25 KB | None | 0 0
  1.  
  2. def get_time(prompt, maxhr):
  3.     while True:
  4.         sin = input("\n" + prompt)
  5.         sinsplit = sin.split(':')
  6.         if len(sinsplit) != 2:
  7.             print("Invalid")
  8.             continue
  9.         if not (sinsplit[0] + sinsplit[1]).isdecimal():
  10.             print("Invalid")
  11.             continue
  12.         h = int(sinsplit[0])
  13.         m = int(sinsplit[1])
  14.         if h > maxhr or m > 59:
  15.             print("Invalid")
  16.             continue
  17.         break
  18.     return h, m
  19.  
  20.  
  21. while True:
  22.     hh, mm = get_time("Enter start time as hh:mm in 12-hour clock format: ", 12)
  23.     while True:
  24.         ap = input("Enter 'am' or 'pm': ").lower()
  25.         if ap in ["am", "pm"]:
  26.             break
  27.         print("Invalid")
  28.     if hh == 0 and ap == "pm":
  29.         print("Invalid")
  30.         continue
  31.     break
  32.  
  33. # Convert start time to 24-hour format
  34.  
  35. if ap == "pm" and hh < 12:
  36.     hh += 12
  37. if ap == "am" and hh == 12:
  38.     hh = 0
  39.  
  40. print(f"Start time is: {hh:02d}:{mm:02d}")
  41.  
  42. dh, dm = get_time("Enter duration as hh:mm (max 24 hours): ", 23)
  43. mm += dm
  44. hplus, mm = divmod(mm, 60)
  45. hh += dh
  46. hh += hplus
  47.  
  48. ap = "am"
  49. hh = hh % 24
  50. if hh > 11:
  51.     ap = "pm"
  52. if hh > 12:
  53.     hh -= 12
  54. if hh == 0:
  55.     hh = 12
  56.  
  57. print(f"Finish time is {hh:02d}:{mm:02d} {ap}")
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement