Skip to content

Instantly share code, notes, and snippets.

@codehack
Created June 26, 2014 19:29
Show Gist options
  • Save codehack/6350492822e52b7fa7fe to your computer and use it in GitHub Desktop.
Save codehack/6350492822e52b7fa7fe to your computer and use it in GitHub Desktop.
ISO8601 date time parser for Python using regex package
#!/usr/bin/python
import re
# i think i missed a couple of things in 8601 but this should cover 98% of cases.
iso8601 = re.compile(r'^(?P<full>((?P<year>\d{4})([/-]?(?P<mon>(0[1-9])|(1[012]))([/-]?(?P<mday>(0[1-9])|([12]\d)|(3[01])))?)?(?:T(?P<hour>([01][0-9])|(?:2[0123]))(\:?(?P<min>[0-5][0-9])(\:?(?P<sec>[0-5][0-9]([\,\.]\d{1,10})?))?)?(?:Z|([\-+](?:([01][0-9])|(?:2[0123]))(\:?(?:[0-5][0-9]))?))?)?))$')
# to perform the actual date match
m = iso8601.match('2014-12-05T12:30:45.123456-05:30')
# prints a dict with all matched groups
print m.groupdict()
# output: {'full': '2014-12-05T12:30:45.123456-05:30', 'mday': '05', 'hour': '12', 'min': '30', 'sec': '45.123456', 'mon': '12', 'year': '2014'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment