How to parse dates for incomplete dates in Python
<p>I am using dateutil.parser to parse dates and I want to throw an exception if the date is incomplete i.e January 1 (missing year) or January 2016 (missing day). So far I have the following </p>

<pre><code>try: 
    parse(date)
    return parse(date).isoformat()
except ValueError:
    return 'invalid'
</code></pre>

<p>You can use private method <code>_parse</code> of class <code>dateutil.parser.parser</code> to determine if day, month and year have been supplied. Since the method is private its behaviour may change and it is generally not advisable to use private methods of other classes in production code, but in this particular case using it is the most easy and robust method, so its probably OK.</p>

<p>Modified code looks like:</p>

<pre><code>from dateutil.parser import parser, parse

# Check if passed date is complete and valid
def is_date_complete (date, must_have_attr=("year","month","day")):
    parse_res, _ = parser()._parse(date)
    # If date is invalid `_parse` returns (None,None)
    if parse_res is None:
        return False
    # For a valid date `_result` object is returned. E.g. _parse("Sep 23") returns (_result(month=9, day=23), None)
    for attr in must_have_attr:
        if getattr(parse_res,attr) is None:
            return False
    return True

## your code section
if not is_date_complete(date):
    return 'invalid'
else:
    return parse(date).isoformat()
</code></pre>

<p>Here we utilized result of <code>_parse</code> to determine if the date has missing year, month or day. </p>

python