Parsing a date in python without using a default

后端 未结 4 556
我寻月下人不归
我寻月下人不归 2021-01-04 05:51

I\'m using python\'s dateutil.parser tool to parse some dates I\'m getting from a third party feed. It allows specifying a default date, which itself defaults

4条回答
  •  别那么骄傲
    2021-01-04 06:44

    This is probably a "hack", but it looks like dateutil looks at very few attributes out of the default you pass in. You could provide a 'fake' datetime that explodes in the desired way.

    >>> import datetime
    >>> import dateutil.parser
    >>> class NoDefaultDate(object):
    ...     def replace(self, **fields):
    ...         if any(f not in fields for f in ('year', 'month', 'day')):
    ...             return None
    ...         return datetime.datetime(2000, 1, 1).replace(**fields)
    >>> def wrap_parse(v):
    ...     _actual = dateutil.parser.parse(v, default=NoDefaultDate())
    ...     return _actual.date() if _actual is not None else None
    >>> cases = (
    ...   ('2011-10-12', datetime.date(2011, 10, 12)),
    ...   ('2011-10', None),
    ...   ('2011', None),
    ...   ('10-12', None),
    ...   ('2011-10-12T11:45:30', datetime.date(2011, 10, 12)),
    ...   ('10-12 11:45', None),
    ...   ('', None),
    ...   )
    >>> all(wrap_parse(test) == expected for test, expected in cases)
    True
    

提交回复
热议问题