From 51ff8dc81eac719ae1119cef340effce3887d5e4 Mon Sep 17 00:00:00 2001 From: Julien Danjou Date: Tue, 18 Feb 2014 16:07:00 +0100 Subject: Raise error on YYYYMM or YYMMDD --- iso8601/iso8601.py | 18 ++++++++++-------- iso8601/test_iso8601.py | 4 ++-- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/iso8601/iso8601.py b/iso8601/iso8601.py index 4907fbd..b1a57e7 100644 --- a/iso8601/iso8601.py +++ b/iso8601/iso8601.py @@ -32,8 +32,8 @@ else: ISO8601_REGEX = re.compile( r""" (?P[0-9]{4}) - (-{0,1}(?P[0-9]{1,2})){1} - (-{0,1}(?P[0-9]{1,2})){1} + ((-(?P[0-9]{1,2}))|(?P[0-9]{2})) + ((-(?P[0-9]{1,2}))|(?P[0-9]{2})) ( ( (?P[ T]) @@ -117,20 +117,22 @@ class FixedOffset(tzinfo): def __repr__(self): return "" % (self.__name, self.__offset) -def to_int(d, key, default_to_zero=False, default=None): +def to_int(d, key, default_to_zero=False, default=None, required=True): """Pull a value from the dict and convert to int :param default_to_zero: If the value is None or empty, treat it as zero :param default: If the value is missing in the dict use this default """ - value = d.get(key, default) + value = d.get(key) or default LOG.debug("Got %r for %r with default %r", value, key, default) if (value in ["", None]) and default_to_zero: return 0 if value is None: - raise ParseError("Unable to read %s from %s" % (key, d)) - return int(value) + if required: + raise ParseError("Unable to read %s from %s" % (key, d)) + else: + return int(value) def parse_timezone(matches, default_timezone=UTC): """Parses ISO 8601 time zone specs into tzinfo offsets @@ -176,8 +178,8 @@ def parse_date(datestring, default_timezone=UTC): try: return datetime( year=to_int(groups, "year"), - month=to_int(groups, "month"), - day=to_int(groups, "day"), + month=to_int(groups, "month", default=to_int(groups, "monthdash", required=False)), + day=to_int(groups, "day", default=to_int(groups, "daydash", required=False)), hour=to_int(groups, "hour", default_to_zero=True), minute=to_int(groups, "minute", default_to_zero=True), second=to_int(groups, "second", default_to_zero=True), diff --git a/iso8601/test_iso8601.py b/iso8601/test_iso8601.py index ffff85d..125f3c7 100644 --- a/iso8601/test_iso8601.py +++ b/iso8601/test_iso8601.py @@ -32,8 +32,8 @@ def test_parse_utc_different_default(): ("", "Unable to parse date string"), (None, "Expecting a string"), ("23", "Unable to parse date string"), - # ("131015T142533Z", "Unable to parse date string"), FIXME - # ("131015", "Unable to parse date string"), FIXME + ("131015T142533Z", "Unable to parse date string"), + ("131015", "Unable to parse date string"), ("2007-06-23X06:40:34.00Z", "Unable to parse date string"), # https://code.google.com/p/pyiso8601/issues/detail?id=14 # ("2007-06-23 06:40:34.00Zrubbish", "Unable to parse date string"), # https://code.google.com/p/pyiso8601/issues/detail?id=14 FIXME ("20114-01-03T01:45:49", "Unable to parse date string"), -- cgit v1.2.1