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 4.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  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. import re
  8. from django.utils.timezone import get_fixed_timezone, utc
  9. date_re = re.compile(
  10. r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$'
  11. )
  12. time_re = re.compile(
  13. r'(?P<hour>\d{1,2}):(?P<minute>\d{1,2})'
  14. r'(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?'
  15. )
  16. datetime_re = re.compile(
  17. r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})'
  18. r'[T ](?P<hour>\d{1,2}):(?P<minute>\d{1,2})'
  19. r'(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?'
  20. r'(?P<tzinfo>Z|[+-]\d{2}(?::?\d{2})?)?$'
  21. )
  22. standard_duration_re = re.compile(
  23. r'^'
  24. r'(?:(?P<days>-?\d+) (days?, )?)?'
  25. r'((?:(?P<hours>-?\d+):)(?=\d+:\d+))?'
  26. r'(?:(?P<minutes>-?\d+):)?'
  27. r'(?P<seconds>-?\d+)'
  28. r'(?:\.(?P<microseconds>\d{1,6})\d{0,6})?'
  29. r'$'
  30. )
  31. # Support the sections of ISO 8601 date representation that are accepted by
  32. # timedelta
  33. iso8601_duration_re = re.compile(
  34. r'^(?P<sign>[-+]?)'
  35. r'P'
  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 = 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. match = date_re.match(value)
  63. if match:
  64. kw = {k: int(v) for k, v in match.groupdict().items()}
  65. return datetime.date(**kw)
  66. def parse_time(value):
  67. """Parse a string and return a datetime.time.
  68. This function doesn't support time zone offsets.
  69. Raise ValueError if the input is well formatted but not a valid time.
  70. Return None if the input isn't well formatted, in particular if it
  71. contains an offset.
  72. """
  73. match = time_re.match(value)
  74. if match:
  75. kw = match.groupdict()
  76. kw['microsecond'] = kw['microsecond'] and kw['microsecond'].ljust(6, '0')
  77. kw = {k: int(v) for k, v in kw.items() if v is not None}
  78. return datetime.time(**kw)
  79. def parse_datetime(value):
  80. """Parse a string and return a datetime.datetime.
  81. This function supports time zone offsets. When the input contains one,
  82. the output uses a timezone with a fixed offset from UTC.
  83. Raise ValueError if the input is well formatted but not a valid datetime.
  84. Return None if the input isn't well formatted.
  85. """
  86. match = datetime_re.match(value)
  87. if match:
  88. kw = match.groupdict()
  89. kw['microsecond'] = kw['microsecond'] and kw['microsecond'].ljust(6, '0')
  90. tzinfo = kw.pop('tzinfo')
  91. if tzinfo == 'Z':
  92. tzinfo = utc
  93. elif tzinfo is not None:
  94. offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0
  95. offset = 60 * int(tzinfo[1:3]) + offset_mins
  96. if tzinfo[0] == '-':
  97. offset = -offset
  98. tzinfo = get_fixed_timezone(offset)
  99. kw = {k: int(v) for k, v in kw.items() if v is not None}
  100. kw['tzinfo'] = tzinfo
  101. return datetime.datetime(**kw)
  102. def parse_duration(value):
  103. """Parse a duration string and return a datetime.timedelta.
  104. The preferred format for durations in Django is '%d %H:%M:%S.%f'.
  105. Also supports ISO 8601 representation and PostgreSQL's day-time interval
  106. format.
  107. """
  108. match = (
  109. standard_duration_re.match(value) or
  110. iso8601_duration_re.match(value) or
  111. postgres_interval_re.match(value)
  112. )
  113. if match:
  114. kw = match.groupdict()
  115. days = datetime.timedelta(float(kw.pop('days', 0) or 0))
  116. sign = -1 if kw.pop('sign', '+') == '-' else 1
  117. if kw.get('microseconds'):
  118. kw['microseconds'] = kw['microseconds'].ljust(6, '0')
  119. if kw.get('seconds') and kw.get('microseconds') and kw['seconds'].startswith('-'):
  120. kw['microseconds'] = '-' + kw['microseconds']
  121. kw = {k: float(v) for k, v in kw.items() if v is not None}
  122. return days + sign * datetime.timedelta(**kw)