dateparse.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 utc, get_fixed_timezone
  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. def parse_date(value):
  24. """Parses a string and return a datetime.date.
  25. Raises ValueError if the input is well formatted but not a valid date.
  26. Returns None if the input isn't well formatted.
  27. """
  28. match = date_re.match(value)
  29. if match:
  30. kw = dict((k, int(v)) for k, v in six.iteritems(match.groupdict()))
  31. return datetime.date(**kw)
  32. def parse_time(value):
  33. """Parses a string and return a datetime.time.
  34. This function doesn't support time zone offsets.
  35. Raises ValueError if the input is well formatted but not a valid time.
  36. Returns None if the input isn't well formatted, in particular if it
  37. contains an offset.
  38. """
  39. match = time_re.match(value)
  40. if match:
  41. kw = match.groupdict()
  42. if kw['microsecond']:
  43. kw['microsecond'] = kw['microsecond'].ljust(6, '0')
  44. kw = dict((k, int(v)) for k, v in six.iteritems(kw) if v is not None)
  45. return datetime.time(**kw)
  46. def parse_datetime(value):
  47. """Parses a string and return a datetime.datetime.
  48. This function supports time zone offsets. When the input contains one,
  49. the output uses a timezone with a fixed offset from UTC.
  50. Raises ValueError if the input is well formatted but not a valid datetime.
  51. Returns None if the input isn't well formatted.
  52. """
  53. match = datetime_re.match(value)
  54. if match:
  55. kw = match.groupdict()
  56. if kw['microsecond']:
  57. kw['microsecond'] = kw['microsecond'].ljust(6, '0')
  58. tzinfo = kw.pop('tzinfo')
  59. if tzinfo == 'Z':
  60. tzinfo = utc
  61. elif tzinfo is not None:
  62. offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0
  63. offset = 60 * int(tzinfo[1:3]) + offset_mins
  64. if tzinfo[0] == '-':
  65. offset = -offset
  66. tzinfo = get_fixed_timezone(offset)
  67. kw = dict((k, int(v)) for k, v in six.iteritems(kw) if v is not None)
  68. kw['tzinfo'] = tzinfo
  69. return datetime.datetime(**kw)