rfc3339_validator.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # -*- coding: utf-8 -*-
  2. __author__ = """Nicolas Aimetti"""
  3. __email__ = 'naimetti@yahoo.com.ar'
  4. __version__ = '0.1.4'
  5. import re
  6. import calendar
  7. import six
  8. RFC3339_REGEX_FLAGS = 0
  9. if six.PY3:
  10. RFC3339_REGEX_FLAGS |= re.ASCII
  11. RFC3339_REGEX = re.compile(r"""
  12. ^
  13. (\d{4}) # Year
  14. -
  15. (0[1-9]|1[0-2]) # Month
  16. -
  17. (\d{2}) # Day
  18. T
  19. (?:[01]\d|2[0123]) # Hours
  20. :
  21. (?:[0-5]\d) # Minutes
  22. :
  23. (?:[0-5]\d) # Seconds
  24. (?:\.\d+)? # Secfrac
  25. (?: Z # UTC
  26. | [+-](?:[01]\d|2[0123]):[0-5]\d # Offset
  27. )
  28. $
  29. """, re.VERBOSE | RFC3339_REGEX_FLAGS)
  30. def validate_rfc3339(date_string):
  31. """
  32. Validates dates against RFC3339 datetime format
  33. Leap seconds are no supported.
  34. """
  35. m = RFC3339_REGEX.match(date_string)
  36. if m is None:
  37. return False
  38. year, month, day = map(int, m.groups())
  39. if not year:
  40. # Year 0 is not valid a valid date
  41. return False
  42. (_, max_day) = calendar.monthrange(year, month)
  43. if not 1 <= day <= max_day:
  44. return False
  45. return True