isotime.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. """
  2. This modules provides a method to parse an ISO 8601:2004 time string to a
  3. Python datetime.time instance.
  4. It supports all basic and extended formats including time zone specifications
  5. as described in the ISO standard.
  6. """
  7. import re
  8. from datetime import time
  9. from decimal import ROUND_FLOOR, Decimal
  10. from isodate.isoerror import ISO8601Error
  11. from isodate.isostrf import TIME_EXT_COMPLETE, TZ_EXT, strftime
  12. from isodate.isotzinfo import TZ_REGEX, build_tzinfo
  13. TIME_REGEX_CACHE = []
  14. # used to cache regular expressions to parse ISO time strings.
  15. def build_time_regexps():
  16. """
  17. Build regular expressions to parse ISO time string.
  18. The regular expressions are compiled and stored in TIME_REGEX_CACHE
  19. for later reuse.
  20. """
  21. if not TIME_REGEX_CACHE:
  22. # ISO 8601 time representations allow decimal fractions on least
  23. # significant time component. Command and Full Stop are both valid
  24. # fraction separators.
  25. # The letter 'T' is allowed as time designator in front of a time
  26. # expression.
  27. # Immediately after a time expression, a time zone definition is
  28. # allowed.
  29. # a TZ may be missing (local time), be a 'Z' for UTC or a string of
  30. # +-hh:mm where the ':mm' part can be skipped.
  31. # TZ information patterns:
  32. # ''
  33. # Z
  34. # +-hh:mm
  35. # +-hhmm
  36. # +-hh =>
  37. # isotzinfo.TZ_REGEX
  38. def add_re(regex_text):
  39. TIME_REGEX_CACHE.append(re.compile(r"\A" + regex_text + TZ_REGEX + r"\Z"))
  40. # 1. complete time:
  41. # hh:mm:ss.ss ... extended format
  42. add_re(
  43. r"T?(?P<hour>[0-9]{2}):"
  44. r"(?P<minute>[0-9]{2}):"
  45. r"(?P<second>[0-9]{2}"
  46. r"([,.][0-9]+)?)"
  47. )
  48. # hhmmss.ss ... basic format
  49. add_re(
  50. r"T?(?P<hour>[0-9]{2})"
  51. r"(?P<minute>[0-9]{2})"
  52. r"(?P<second>[0-9]{2}"
  53. r"([,.][0-9]+)?)"
  54. )
  55. # 2. reduced accuracy:
  56. # hh:mm.mm ... extended format
  57. add_re(r"T?(?P<hour>[0-9]{2}):" r"(?P<minute>[0-9]{2}" r"([,.][0-9]+)?)")
  58. # hhmm.mm ... basic format
  59. add_re(r"T?(?P<hour>[0-9]{2})" r"(?P<minute>[0-9]{2}" r"([,.][0-9]+)?)")
  60. # hh.hh ... basic format
  61. add_re(r"T?(?P<hour>[0-9]{2}" r"([,.][0-9]+)?)")
  62. return TIME_REGEX_CACHE
  63. def parse_time(timestring):
  64. """
  65. Parses ISO 8601 times into datetime.time objects.
  66. Following ISO 8601 formats are supported:
  67. (as decimal separator a ',' or a '.' is allowed)
  68. hhmmss.ssTZD basic complete time
  69. hh:mm:ss.ssTZD extended complete time
  70. hhmm.mmTZD basic reduced accuracy time
  71. hh:mm.mmTZD extended reduced accuracy time
  72. hh.hhTZD basic reduced accuracy time
  73. TZD is the time zone designator which can be in the following format:
  74. no designator indicates local time zone
  75. Z UTC
  76. +-hhmm basic hours and minutes
  77. +-hh:mm extended hours and minutes
  78. +-hh hours
  79. """
  80. isotimes = build_time_regexps()
  81. for pattern in isotimes:
  82. match = pattern.match(timestring)
  83. if match:
  84. groups = match.groupdict()
  85. for key, value in groups.items():
  86. if value is not None:
  87. groups[key] = value.replace(",", ".")
  88. tzinfo = build_tzinfo(
  89. groups["tzname"],
  90. groups["tzsign"],
  91. int(groups["tzhour"] or 0),
  92. int(groups["tzmin"] or 0),
  93. )
  94. if "second" in groups:
  95. second = Decimal(groups["second"]).quantize(
  96. Decimal(".000001"), rounding=ROUND_FLOOR
  97. )
  98. microsecond = (second - int(second)) * int(1e6)
  99. # int(...) ... no rounding
  100. # to_integral() ... rounding
  101. return time(
  102. int(groups["hour"]),
  103. int(groups["minute"]),
  104. int(second),
  105. int(microsecond.to_integral()),
  106. tzinfo,
  107. )
  108. if "minute" in groups:
  109. minute = Decimal(groups["minute"])
  110. second = Decimal((minute - int(minute)) * 60).quantize(
  111. Decimal(".000001"), rounding=ROUND_FLOOR
  112. )
  113. microsecond = (second - int(second)) * int(1e6)
  114. return time(
  115. int(groups["hour"]),
  116. int(minute),
  117. int(second),
  118. int(microsecond.to_integral()),
  119. tzinfo,
  120. )
  121. else:
  122. microsecond, second, minute = 0, 0, 0
  123. hour = Decimal(groups["hour"])
  124. minute = (hour - int(hour)) * 60
  125. second = (minute - int(minute)) * 60
  126. microsecond = (second - int(second)) * int(1e6)
  127. return time(
  128. int(hour),
  129. int(minute),
  130. int(second),
  131. int(microsecond.to_integral()),
  132. tzinfo,
  133. )
  134. raise ISO8601Error("Unrecognised ISO 8601 time format: %r" % timestring)
  135. def time_isoformat(ttime, format=TIME_EXT_COMPLETE + TZ_EXT):
  136. """
  137. Format time strings.
  138. This method is just a wrapper around isodate.isostrf.strftime and uses
  139. Time-Extended-Complete with extended time zone as default format.
  140. """
  141. return strftime(ttime, format)