Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dateparse.py 5.2KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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<days>\d+([\.,]\d+)?)D)?"
  36. r"(?:T"
  37. r"(?:(?P<hours>\d+([\.,]\d+)?)H)?"
  38. r"(?:(?P<minutes>\d+([\.,]\d+)?)M)?"
  39. r"(?:(?P<seconds>\d+([\.,]\d+)?)S)?"
  40. r")?"
  41. r"$"
  42. )
  43. # Support PostgreSQL's day-time interval format, e.g. "3 days 04:05:06". The
  44. # year-month and mixed intervals cannot be converted to a timedelta and thus
  45. # aren't accepted.
  46. postgres_interval_re = _lazy_re_compile(
  47. r"^"
  48. r"(?:(?P<days>-?\d+) (days? ?))?"
  49. r"(?:(?P<sign>[-+])?"
  50. r"(?P<hours>\d+):"
  51. r"(?P<minutes>\d\d):"
  52. r"(?P<seconds>\d\d)"
  53. r"(?:\.(?P<microseconds>\d{1,6}))?"
  54. r")?$"
  55. )
  56. def parse_date(value):
  57. """Parse a string and return a datetime.date.
  58. Raise ValueError if the input is well formatted but not a valid date.
  59. Return None if the input isn't well formatted.
  60. """
  61. try:
  62. return datetime.date.fromisoformat(value)
  63. except ValueError:
  64. if match := date_re.match(value):
  65. kw = {k: int(v) for k, v in match.groupdict().items()}
  66. return datetime.date(**kw)
  67. def parse_time(value):
  68. """Parse a string and return a datetime.time.
  69. This function doesn't support time zone offsets.
  70. Raise ValueError if the input is well formatted but not a valid time.
  71. Return None if the input isn't well formatted, in particular if it
  72. contains an offset.
  73. """
  74. try:
  75. # The fromisoformat() method takes time zone info into account and
  76. # returns a time with a tzinfo component, if possible. However, there
  77. # are no circumstances where aware datetime.time objects make sense, so
  78. # remove the time zone offset.
  79. return datetime.time.fromisoformat(value).replace(tzinfo=None)
  80. except ValueError:
  81. if match := time_re.match(value):
  82. kw = match.groupdict()
  83. kw["microsecond"] = kw["microsecond"] and kw["microsecond"].ljust(6, "0")
  84. kw = {k: int(v) for k, v in kw.items() if v is not None}
  85. return datetime.time(**kw)
  86. def parse_datetime(value):
  87. """Parse a string and return a datetime.datetime.
  88. This function supports time zone offsets. When the input contains one,
  89. the output uses a timezone with a fixed offset from UTC.
  90. Raise ValueError if the input is well formatted but not a valid datetime.
  91. Return None if the input isn't well formatted.
  92. """
  93. try:
  94. return datetime.datetime.fromisoformat(value)
  95. except ValueError:
  96. if match := datetime_re.match(value):
  97. kw = match.groupdict()
  98. kw["microsecond"] = kw["microsecond"] and kw["microsecond"].ljust(6, "0")
  99. tzinfo = kw.pop("tzinfo")
  100. if tzinfo == "Z":
  101. tzinfo = datetime.timezone.utc
  102. elif tzinfo is not None:
  103. offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0
  104. offset = 60 * int(tzinfo[1:3]) + offset_mins
  105. if tzinfo[0] == "-":
  106. offset = -offset
  107. tzinfo = get_fixed_timezone(offset)
  108. kw = {k: int(v) for k, v in kw.items() if v is not None}
  109. return datetime.datetime(**kw, tzinfo=tzinfo)
  110. def parse_duration(value):
  111. """Parse a duration string and return a datetime.timedelta.
  112. The preferred format for durations in Django is '%d %H:%M:%S.%f'.
  113. Also supports ISO 8601 representation and PostgreSQL's day-time interval
  114. format.
  115. """
  116. match = (
  117. standard_duration_re.match(value)
  118. or iso8601_duration_re.match(value)
  119. or postgres_interval_re.match(value)
  120. )
  121. if match:
  122. kw = match.groupdict()
  123. sign = -1 if kw.pop("sign", "+") == "-" else 1
  124. if kw.get("microseconds"):
  125. kw["microseconds"] = kw["microseconds"].ljust(6, "0")
  126. kw = {k: float(v.replace(",", ".")) for k, v in kw.items() if v is not None}
  127. days = datetime.timedelta(kw.pop("days", 0.0) or 0.0)
  128. if match.re == iso8601_duration_re:
  129. days *= sign
  130. return days + sign * datetime.timedelta(**kw)