iso8601.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. """Parse ISO8601 dates.
  2. Originally taken from :pypi:`pyiso8601`
  3. (https://bitbucket.org/micktwomey/pyiso8601)
  4. Modified to match the behavior of ``dateutil.parser``:
  5. - raise :exc:`ValueError` instead of ``ParseError``
  6. - return naive :class:`~datetime.datetime` by default
  7. - uses :class:`pytz.FixedOffset`
  8. This is the original License:
  9. Copyright (c) 2007 Michael Twomey
  10. Permission is hereby granted, free of charge, to any person obtaining a
  11. copy of this software and associated documentation files (the
  12. "Software"), to deal in the Software without restriction, including
  13. without limitation the rights to use, copy, modify, merge, publish,
  14. distribute, sub-license, and/or sell copies of the Software, and to
  15. permit persons to whom the Software is furnished to do so, subject to
  16. the following conditions:
  17. The above copyright notice and this permission notice shall be included
  18. in all copies or substantial portions of the Software.
  19. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  20. OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  21. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  22. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  23. CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  24. TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  25. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  26. """
  27. from __future__ import absolute_import, unicode_literals
  28. import re
  29. from datetime import datetime
  30. from pytz import FixedOffset
  31. __all__ = ('parse_iso8601',)
  32. # Adapted from http://delete.me.uk/2005/03/iso8601.html
  33. ISO8601_REGEX = re.compile(
  34. r'(?P<year>[0-9]{4})(-(?P<month>[0-9]{1,2})(-(?P<day>[0-9]{1,2})'
  35. r'((?P<separator>.)(?P<hour>[0-9]{2}):(?P<minute>[0-9]{2})'
  36. r'(:(?P<second>[0-9]{2})(\.(?P<fraction>[0-9]+))?)?'
  37. r'(?P<timezone>Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?'
  38. )
  39. TIMEZONE_REGEX = re.compile(
  40. r'(?P<prefix>[+-])(?P<hours>[0-9]{2}).(?P<minutes>[0-9]{2})'
  41. )
  42. def parse_iso8601(datestring):
  43. """Parse and convert ISO-8601 string to datetime."""
  44. m = ISO8601_REGEX.match(datestring)
  45. if not m:
  46. raise ValueError('unable to parse date string %r' % datestring)
  47. groups = m.groupdict()
  48. tz = groups['timezone']
  49. if tz == 'Z':
  50. tz = FixedOffset(0)
  51. elif tz:
  52. m = TIMEZONE_REGEX.match(tz)
  53. prefix, hours, minutes = m.groups()
  54. hours, minutes = int(hours), int(minutes)
  55. if prefix == '-':
  56. hours = -hours
  57. minutes = -minutes
  58. tz = FixedOffset(minutes + hours * 60)
  59. return datetime(
  60. int(groups['year']), int(groups['month']),
  61. int(groups['day']), int(groups['hour'] or 0),
  62. int(groups['minute'] or 0), int(groups['second'] or 0),
  63. int(groups['fraction'] or 0), tz
  64. )