3

I am getting a very strange bug in python.

from dateutil import parser
string = "March 2008"
parser.parse(string)
 datetime.datetime(2008, 3, 30, 0, 0)
string = "February 2008"
parser.parse(string)

Traceback (most recent call last):

File "", line 1, in File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/dateutil/parser.py", line 697, in parse return DEFAULTPARSER.parse(timestr, **kwargs) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/dateutil/parser.py", line 310, in parse ret = default.replace(**repl) ValueError: day is out of range for month

I understand that I can add a day to my string to make the parser work, but I have no idea why dateutil does not work without the day for February, while it works for every other month.

4

2 回答 2

4

这是一个有趣的。

来自 dateutil.parser:

    def parse(self, timestr, default=None,
                ignoretz=False, tzinfos=None,
                **kwargs):
    if not default:
        default = datetime.datetime.now().replace(hour=0, minute=0,
                                                  second=0, microsecond=0)

基本上,如果您不提供日期,则任何缺少日期的日期字符串都将默认为当天。碰巧的是,今天是 30 日,当然 2 月没有。这可能被认为是 dateutil 中的一个错误。

于 2014-07-30T19:18:27.783 回答
1

问题是解析字符串中不存在的任何字段都取自当前日期。

请注意,“2008 年 3 月”返回 2008 年 3 月 30 日,因为您在 2014 年 7 月 30 日运行它。

同样,仅“三月”将为您提供 2014 年 3 月 30 日。

因此,“2008 年 2 月”将给您 2008 年 2 月 30 日,这当然是无效的。

于 2014-07-30T19:15:06.140 回答