Parsing a date in python without using a default

后端 未结 4 558
我寻月下人不归
我寻月下人不归 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:49

    Depending on your domain following solution might work:

    DEFAULT_DATE = datetime.datetime(datetime.MINYEAR, 1, 1)
    
    def parse_no_default(dt_str):    
        dt = parser.parse(dt_str, default=DEFAULT_DATE).date()
        if dt != DEFAULT_DATE:
           return dt
        else:
           return None
    

    Another approach would be to monkey patch parser class (this is very hackiesh, so I wouldn't recommend it if you have other options):

    import dateutil.parser as parser
    def parse(self, timestr, default=None,
              ignoretz=False, tzinfos=None,
              **kwargs):
        return self._parse(timestr, **kwargs)
    parser.parser.parse = parse
    

    You can use it as follows:

    >>> ffffd = parser.parser().parse('2011-01-02', None)
    >>> ffffd
    _result(year=2011, month=01, day=02)
    >>> ffffd = parser.parser().parse('2011', None)
    >>> ffffd
    _result(year=2011)
    

    By checking which members available in result (ffffd) you could determine when return None. When all fields available you can convert ffffd into datetime object:

    # ffffd might have following fields:
    # "year", "month", "day", "weekday",
    # "hour", "minute", "second", "microsecond",
    # "tzname", "tzoffset"
    datetime.datetime(ffffd.year, ffffd.month, ffffd.day)
    

提交回复
热议问题