dateparse.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. """Functions to parse datetime objects."""
  2. # We're using regular expressions rather than time.strptime because:
  3. # - They provide both validation and parsing.
  4. # - They're more flexible for datetimes.
  5. # - The date/datetime/time constructors produce friendlier error messages.
  6. import datetime
  7. from django.utils.regex_helper import _lazy_re_compile
  8. from django.utils.timezone import get_fixed_timezone
  9. date_re = _lazy_re_compile(r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$")
  10. time_re = _lazy_re_compile(
  11. r"(?P<hour>\d{1,2}):(?P<minute>\d{1,2})"
  12. r"(?::(?P<second>\d{1,2})(?:[.,](?P<microsecond>\d{1,6})\d{0,6})?)?$"
  13. )
  14. datetime_re = _lazy_re_compile(
  15. r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})"
  16. r"[T ](?P<hour>\d{1,2}):(?P<minute>\d{1,2})"
  17. r"(?::(?P<second>\d{1,2})(?:[.,](?P<microsecond>\d{1,6})\d{0,6})?)?"
  18. r"\s*(?P<tzinfo>Z|[+-]\d{2}(?::?\d{2})?)?$"
  19. )
  20. standard_duration_re = _lazy_re_compile(
  21. r"^"
  22. r"(?:(?P<days>-?\d+) (days?, )?)?"
  23. r"(?P<sign>-?)"
  24. r"((?:(?P<hours>\d+):)(?=\d+:\d+))?"
  25. r"(?:(?P<minutes>\d+):)?"
  26. r"(?P<seconds>\d+)"
  27. r"(?:[.,](?P<microseconds>\d{1,6})\d{0,6})?"
  28. r"$"
  29. )
  30. # Support the sections of ISO 8601 date representation that are accepted by
  31. # timedelta
  32. iso8601_duration_re = _lazy_re_compile(
  33. r"^(?P<sign>[-+]?)"
  34. r"P"
  35. r"(?:(?P<weeks>\d+([.,]\d+)?)W)?"
  36. r"(?:(?P<days>\d+([.,]\d+)?)D)?"
  37. r"(?:T"
  38. r"(?:(?P<hours>\d+([.,]\d+)?)H)?"
  39. r"(?:(?P<minutes>\d+([.,]\d+)?)M)?"
  40. r"(?:(?P<seconds>\d+([.,]\d+)?)S)?"
  41. r")?"
  42. r"$"
  43. )
  44. # Support PostgreSQL's day-time interval format, e.g. "3 days 04:05:06". The
  45. # year-month and mixed intervals cannot be converted to a timedelta and thus
  46. # aren't accepted.
  47. postgres_interval_re = _lazy_re_compile(
  48. r"^"
  49. r"(?:(?P<days>-?\d+) (days? ?))?"
  50. r"(?:(?P<sign>[-+])?"
  51. r"(?P<hours>\d+):"
  52. r"(?P<minutes>\d\d):"
  53. r"(?P<seconds>\d\d)"
  54. r"(?:\.(?P<microseconds>\d{1,6}))?"
  55. r")?$"
  56. )
  57. def parse_date(value):
  58. """Parse a string and return a datetime.date.
  59. Raise ValueError if the input is well formatted but not a valid date.
  60. Return None if the input isn't well formatted.
  61. """
  62. try:
  63. return datetime.date.fromisoformat(value)
  64. except ValueError:
  65. if match := date_re.match(value):
  66. kw = {k: int(v) for k, v in match.groupdict().items()}
  67. return datetime.date(**kw)
  68. def parse_time(value):
  69. """Parse a string and return a datetime.time.
  70. This function doesn't support time zone offsets.
  71. Raise ValueError if the input is well formatted but not a valid time.
  72. Return None if the input isn't well formatted, in particular if it
  73. contains an offset.
  74. """
  75. try:
  76. # The fromisoformat() method takes time zone info into account and
  77. # returns a time with a tzinfo component, if possible. However, there
  78. # are no circumstances where aware datetime.time objects make sense, so
  79. # remove the time zone offset.
  80. return datetime.time.fromisoformat(value).replace(tzinfo=None)
  81. except ValueError:
  82. if match := time_re.match(value):
  83. kw = match.groupdict()
  84. kw["microsecond"] = kw["microsecond"] and kw["microsecond"].ljust(6, "0")
  85. kw = {k: int(v) for k, v in kw.items() if v is not None}
  86. return datetime.time(**kw)
  87. def parse_datetime(value):
  88. """Parse a string and return a datetime.datetime.
  89. This function supports time zone offsets. When the input contains one,
  90. the output uses a timezone with a fixed offset from UTC.
  91. Raise ValueError if the input is well formatted but not a valid datetime.
  92. Return None if the input isn't well formatted.
  93. """
  94. try:
  95. return datetime.datetime.fromisoformat(value)
  96. except ValueError:
  97. if match := datetime_re.match(value):
  98. kw = match.groupdict()
  99. kw["microsecond"] = kw["microsecond"] and kw["microsecond"].ljust(6, "0")
  100. tzinfo = kw.pop("tzinfo")
  101. if tzinfo == "Z":
  102. tzinfo = datetime.UTC
  103. elif tzinfo is not None:
  104. offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0
  105. offset = 60 * int(tzinfo[1:3]) + offset_mins
  106. if tzinfo[0] == "-":
  107. offset = -offset
  108. tzinfo = get_fixed_timezone(offset)
  109. kw = {k: int(v) for k, v in kw.items() if v is not None}
  110. return datetime.datetime(**kw, tzinfo=tzinfo)
  111. def parse_duration(value):
  112. """Parse a duration string and return a datetime.timedelta.
  113. The preferred format for durations in Django is '%d %H:%M:%S.%f'.
  114. Also supports ISO 8601 representation (excluding years and months) and
  115. PostgreSQL's day-time interval format.
  116. """
  117. match = (
  118. standard_duration_re.match(value)
  119. or iso8601_duration_re.match(value)
  120. or postgres_interval_re.match(value)
  121. )
  122. if match:
  123. kw = match.groupdict()
  124. sign = -1 if kw.pop("sign", "+") == "-" else 1
  125. if kw.get("microseconds"):
  126. kw["microseconds"] = kw["microseconds"].ljust(6, "0")
  127. kw = {k: float(v.replace(",", ".")) for k, v in kw.items() if v is not None}
  128. days = datetime.timedelta(kw.pop("days", 0.0) or 0.0)
  129. if match.re == iso8601_duration_re:
  130. days *= sign
  131. return days + sign * datetime.timedelta(**kw)