isotzinfo.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. """
  2. This module provides an ISO 8601:2004 time zone info parser.
  3. It offers a function to parse the time zone offset as specified by ISO 8601.
  4. """
  5. import re
  6. from isodate.isoerror import ISO8601Error
  7. from isodate.tzinfo import UTC, ZERO, FixedOffset
  8. TZ_REGEX = (
  9. r"(?P<tzname>(Z|(?P<tzsign>[+-])" r"(?P<tzhour>[0-9]{2})(:?(?P<tzmin>[0-9]{2}))?)?)"
  10. )
  11. TZ_RE = re.compile(TZ_REGEX)
  12. def build_tzinfo(tzname, tzsign="+", tzhour=0, tzmin=0):
  13. """
  14. create a tzinfo instance according to given parameters.
  15. tzname:
  16. 'Z' ... return UTC
  17. '' | None ... return None
  18. other ... return FixedOffset
  19. """
  20. if tzname is None or tzname == "":
  21. return None
  22. if tzname == "Z":
  23. return UTC
  24. tzsign = ((tzsign == "-") and -1) or 1
  25. return FixedOffset(tzsign * tzhour, tzsign * tzmin, tzname)
  26. def parse_tzinfo(tzstring):
  27. """
  28. Parses ISO 8601 time zone designators to tzinfo objects.
  29. A time zone designator can be in the following format:
  30. no designator indicates local time zone
  31. Z UTC
  32. +-hhmm basic hours and minutes
  33. +-hh:mm extended hours and minutes
  34. +-hh hours
  35. """
  36. match = TZ_RE.match(tzstring)
  37. if match:
  38. groups = match.groupdict()
  39. return build_tzinfo(
  40. groups["tzname"],
  41. groups["tzsign"],
  42. int(groups["tzhour"] or 0),
  43. int(groups["tzmin"] or 0),
  44. )
  45. raise ISO8601Error("%s not a valid time zone info" % tzstring)
  46. def tz_isoformat(dt, format="%Z"):
  47. """
  48. return time zone offset ISO 8601 formatted.
  49. The various ISO formats can be chosen with the format parameter.
  50. if tzinfo is None returns ''
  51. if tzinfo is UTC returns 'Z'
  52. else the offset is rendered to the given format.
  53. format:
  54. %h ... +-HH
  55. %z ... +-HHMM
  56. %Z ... +-HH:MM
  57. """
  58. tzinfo = dt.tzinfo
  59. if (tzinfo is None) or (tzinfo.utcoffset(dt) is None):
  60. return ""
  61. if tzinfo.utcoffset(dt) == ZERO and tzinfo.dst(dt) == ZERO:
  62. return "Z"
  63. tdelta = tzinfo.utcoffset(dt)
  64. seconds = tdelta.days * 24 * 60 * 60 + tdelta.seconds
  65. sign = ((seconds < 0) and "-") or "+"
  66. seconds = abs(seconds)
  67. minutes, seconds = divmod(seconds, 60)
  68. hours, minutes = divmod(minutes, 60)
  69. if hours > 99:
  70. raise OverflowError("can not handle differences > 99 hours")
  71. if format == "%Z":
  72. return "%s%02d:%02d" % (sign, hours, minutes)
  73. elif format == "%z":
  74. return "%s%02d%02d" % (sign, hours, minutes)
  75. elif format == "%h":
  76. return "%s%02d" % (sign, hours)
  77. raise ValueError('unknown format string "%s"' % format)