timezone.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2021, Brandon Nielsen
  3. # All rights reserved.
  4. #
  5. # This software may be modified and distributed under the terms
  6. # of the BSD license. See the LICENSE file for details.
  7. from aniso8601.builders.python import PythonTimeBuilder
  8. from aniso8601.compat import is_string
  9. from aniso8601.exceptions import ISOFormatError
  10. def parse_timezone(tzstr, builder=PythonTimeBuilder):
  11. # tzstr can be Z, ±hh:mm, ±hhmm, ±hh
  12. if is_string(tzstr) is False:
  13. raise ValueError("Time zone must be string.")
  14. if len(tzstr) == 1 and tzstr[0] == "Z":
  15. return builder.build_timezone(negative=False, Z=True, name=tzstr)
  16. elif len(tzstr) == 6:
  17. # ±hh:mm
  18. hourstr = tzstr[1:3]
  19. minutestr = tzstr[4:6]
  20. if tzstr[0] == "-" and hourstr == "00" and minutestr == "00":
  21. raise ISOFormatError("Negative ISO 8601 time offset must not " "be 0.")
  22. elif len(tzstr) == 5:
  23. # ±hhmm
  24. hourstr = tzstr[1:3]
  25. minutestr = tzstr[3:5]
  26. if tzstr[0] == "-" and hourstr == "00" and minutestr == "00":
  27. raise ISOFormatError("Negative ISO 8601 time offset must not " "be 0.")
  28. elif len(tzstr) == 3:
  29. # ±hh
  30. hourstr = tzstr[1:3]
  31. minutestr = None
  32. if tzstr[0] == "-" and hourstr == "00":
  33. raise ISOFormatError("Negative ISO 8601 time offset must not " "be 0.")
  34. else:
  35. raise ISOFormatError('"{0}" is not a valid ISO 8601 time offset.'.format(tzstr))
  36. for componentstr in [hourstr, minutestr]:
  37. if componentstr is not None:
  38. if componentstr.isdigit() is False:
  39. raise ISOFormatError(
  40. '"{0}" is not a valid ISO 8601 time offset.'.format(tzstr)
  41. )
  42. if tzstr[0] == "+":
  43. return builder.build_timezone(
  44. negative=False, hh=hourstr, mm=minutestr, name=tzstr
  45. )
  46. if tzstr[0] == "-":
  47. return builder.build_timezone(
  48. negative=True, hh=hourstr, mm=minutestr, name=tzstr
  49. )
  50. raise ISOFormatError('"{0}" is not a valid ISO 8601 time offset.'.format(tzstr))