0

I'm writing an API and I would like to accept ISO 8601 format for date and time. I want to accept only that format. I'm using dateutil at the moment, but its parse function accepts all manner of formats unrelated to ISO8601. I have a simple regex checking the format now, but the actual standard allows a lot more than what my regex does.

Is there a simple function/module which provides a way to parse only 8601 formatted dates/times?

edA-qa mort-ora-y
  • 30,295
  • 39
  • 137
  • 267
  • 3
    https://pypi.python.org/pypi/iso8601 is it so hard to search for it? – Loïc Faure-Lacroix Feb 07 '14 at 05:25
  • It has that "where it differs" section which means it allows some non-ISO8601 formats through. – edA-qa mort-ora-y Feb 07 '14 at 05:41
  • 1
    A google search for iso8601 format regex led me to this SO question: http://stackoverflow.com/questions/12756159/regex-and-iso8601-formated-datetime. One of the answers suggests this regex: /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/ – Jayanth Koushik Feb 07 '14 at 05:57
  • @edA-qamort-ora-y the code is open, you can fix it. – Loïc Faure-Lacroix Feb 07 '14 at 06:06

1 Answers1

0

You can use datetime.datetime.strptime, which will give an error if it cannot parse against the format you specify:

from datetime import datetime

def parse_8601(s):
    """Parses date string if in an ISO 8601 format, else returns None."""
    for f in ["%Y-%m-%dT%H:%M:%S", ...]: # acceptable formats
        try:
            return datetime.strptime(s, f)
        except ValueError:
            pass
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437