Queer European MD passionate about IT

working.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import re
  2. american_time_regex = re.compile(r"^\s*(\d+)(?:\:(\d{2}))? ([AP])M to (\d+)(?:\:(\d{2}))? ([AP])\s*M$")
  3. def main():
  4. print(convert(input("Hours: ")))
  5. def convert(s):
  6. time = american_time_regex.match(s)
  7. if time is None:
  8. raise ValueError("Invalid input time")
  9. if len(time.groups()) == 4:
  10. start_h, start_ampm, end_h, end_ampm = time.groups()
  11. start_m, end_m = 0, 0
  12. else:
  13. start_h, start_m, start_ampm, end_h, end_m, end_ampm = time.groups()
  14. start_m, end_m = map(lambda x: int(x) if x else 0, (start_m, end_m))
  15. start_h, end_h = map(int, (start_h, end_h))
  16. if start_h > 12 or end_h > 12:
  17. raise ValueError
  18. if (start_ampm == 'P' and start_h != 12) or (start_ampm == 'A' and start_h == 12):
  19. start_h += 12
  20. if (end_ampm == 'P' and end_h != 12) or (end_ampm == 'A' and end_h == 12):
  21. end_h += 12
  22. if start_h > 24 or end_h > 24 or start_m > 59 or end_m > 59:
  23. raise ValueError
  24. start_h = start_h % 24
  25. end_h = end_h % 24
  26. return f"{start_h:0>2}:{start_m:0>2} to {end_h:0>2}:{end_m:0>2}"
  27. ...
  28. if __name__ == "__main__":
  29. main()