Advertisement
Peaser

clock converter

Feb 8th, 2016
406
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.49 KB | None | 0 0
  1. import regex, sys
  2.  
  3. ### Script that turns 24 hr clock string into 12 hr clock string with AM/PM ###
  4.  
  5. time = sys.argv[1]
  6. pattern = "(\d{1,2}):(\d{1,2})"
  7.  
  8. #~~~~~~~~~~~~~~~~~~~#
  9.  
  10. #Error check no.1
  11. try:
  12.   result = list(regex.findall(pattern, time)[0])
  13.  
  14.   #Error check no.2 (nested!)
  15.   if len(result) != 2:
  16.     print("Input cannot be parsed. Please format like this: `##:##`.")
  17.     sys.exit(-1)
  18. except:
  19.   print("Input cannot be parsed. Please format like this: `##:##`.")
  20.   sys.exit(-1)
  21.  
  22. result = [int(i) for i in result]
  23.  
  24. #~~~~~~~~~~~~~~~~~~~#
  25.  
  26. #Failure detection system (Error check no.3)
  27. failureReasons = {
  28.   "Hours too high.":   (result[0] > 23),
  29.   "Minutes too high.": (result[1] > 59)
  30. }
  31. Failures = [i for i in failureReasons if failureReasons[i]]
  32. if Failures:
  33.  
  34.   #Lists any errors like this:
  35.   #     [!] Reason 1
  36.   #     [!] Reason 2
  37.   print("Unable to run because of the following:\n{}".format("\n".join(["\t[!] " + i for i in Failures])))
  38.   sys.exit(-1)
  39.  
  40. #~~~~~~~~~~~~~~~~~~~#
  41.  
  42. def main():
  43.   if result[0] > 12:
  44.     result[0] -= 12
  45.     result.append("PM")
  46.   else:
  47.     result.append("AM")
  48.  
  49.   #Formats `result` array into a string
  50.   #Prepends "0" to `m` if it doesn't have one, so that it appears as "2:04" for example, instead of "2:4".
  51.   timeformatter = lambda h, m ,suf: "{}:{} {}".format(h, "0"+str(m) if len(str(m)) == 1 else m, suf)
  52.  
  53.   print("Time (12hr): {output}".format(output=timeformatter(*result)))
  54.  
  55. #~~~~~~~~~~~~~~~~~~~#
  56.  
  57. if __name__ == '__main__':
  58.   main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement