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.
 
 
 
 

128 lines
3.9 KiB

  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 import six
  9. from django.utils.timezone import get_fixed_timezone, utc
  10. date_re = re.compile(
  11. r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$'
  12. )
  13. time_re = re.compile(
  14. r'(?P<hour>\d{1,2}):(?P<minute>\d{1,2})'
  15. r'(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?'
  16. )
  17. datetime_re = re.compile(
  18. r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})'
  19. r'[T ](?P<hour>\d{1,2}):(?P<minute>\d{1,2})'
  20. r'(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?'
  21. r'(?P<tzinfo>Z|[+-]\d{2}(?::?\d{2})?)?$'
  22. )
  23. standard_duration_re = re.compile(
  24. r'^'
  25. r'(?:(?P<days>-?\d+) (days?, )?)?'
  26. r'((?:(?P<hours>\d+):)(?=\d+:\d+))?'
  27. r'(?:(?P<minutes>\d+):)?'
  28. r'(?P<seconds>\d+)'
  29. r'(?:\.(?P<microseconds>\d{1,6})\d{0,6})?'
  30. r'$'
  31. )
  32. # Support the sections of ISO 8601 date representation that are accepted by
  33. # timedelta
  34. iso8601_duration_re = re.compile(
  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. def parse_date(value):
  45. """Parses a string and return a datetime.date.
  46. Raises ValueError if the input is well formatted but not a valid date.
  47. Returns None if the input isn't well formatted.
  48. """
  49. match = date_re.match(value)
  50. if match:
  51. kw = {k: int(v) for k, v in six.iteritems(match.groupdict())}
  52. return datetime.date(**kw)
  53. def parse_time(value):
  54. """Parses a string and return a datetime.time.
  55. This function doesn't support time zone offsets.
  56. Raises ValueError if the input is well formatted but not a valid time.
  57. Returns None if the input isn't well formatted, in particular if it
  58. contains an offset.
  59. """
  60. match = time_re.match(value)
  61. if match:
  62. kw = match.groupdict()
  63. if kw['microsecond']:
  64. kw['microsecond'] = kw['microsecond'].ljust(6, '0')
  65. kw = {k: int(v) for k, v in six.iteritems(kw) if v is not None}
  66. return datetime.time(**kw)
  67. def parse_datetime(value):
  68. """Parses a string and return a datetime.datetime.
  69. This function supports time zone offsets. When the input contains one,
  70. the output uses a timezone with a fixed offset from UTC.
  71. Raises ValueError if the input is well formatted but not a valid datetime.
  72. Returns None if the input isn't well formatted.
  73. """
  74. match = datetime_re.match(value)
  75. if match:
  76. kw = match.groupdict()
  77. if kw['microsecond']:
  78. kw['microsecond'] = kw['microsecond'].ljust(6, '0')
  79. tzinfo = kw.pop('tzinfo')
  80. if tzinfo == 'Z':
  81. tzinfo = utc
  82. elif tzinfo is not None:
  83. offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0
  84. offset = 60 * int(tzinfo[1:3]) + offset_mins
  85. if tzinfo[0] == '-':
  86. offset = -offset
  87. tzinfo = get_fixed_timezone(offset)
  88. kw = {k: int(v) for k, v in six.iteritems(kw) if v is not None}
  89. kw['tzinfo'] = tzinfo
  90. return datetime.datetime(**kw)
  91. def parse_duration(value):
  92. """Parses a duration string and returns a datetime.timedelta.
  93. The preferred format for durations in Django is '%d %H:%M:%S.%f'.
  94. Also supports ISO 8601 representation.
  95. """
  96. match = standard_duration_re.match(value)
  97. if not match:
  98. match = iso8601_duration_re.match(value)
  99. if match:
  100. kw = match.groupdict()
  101. if kw.get('microseconds'):
  102. kw['microseconds'] = kw['microseconds'].ljust(6, '0')
  103. kw = {k: float(v) for k, v in six.iteritems(kw) if v is not None}
  104. return datetime.timedelta(**kw)