简体   繁体   English

Python dateutil.parser抛出“ValueError:day超出范围的月份”

[英]Python dateutil.parser throws “ValueError: day is out of range for month”

I have a the following code that runs fine with input format like {Year}/{Month} except when it comes to 1994/02 我有一个以下代码可以正常运行,输入格式如{Year}/{Month}除了1994/02

Here is the sample code 这是示例代码

>>> import dateutil.parser as dtp
>>> dtp.parse('1994/01')
datetime.datetime(1994, 1, 29, 0, 0)
>>> dtp.parse('1994/03')
datetime.datetime(1994, 3, 29, 0, 0)
>>> dtp.parse('1994/02')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/antony/.virtualenvs/comp-invest/lib/python2.7/site-packages/dateutil/parser.py", line 720, in parse
    return DEFAULTPARSER.parse(timestr, **kwargs)
  File "/Users/antony/.virtualenvs/comp-invest/lib/python2.7/site-packages/dateutil/parser.py", line 317, in parse
    ret = default.replace(**repl)
ValueError: day is out of range for month

As you can see, the code works fine with 1994/01 and 1994/03 , but fails with 1994/02 Does this have anything to do with leap year? 正如你所看到的,代码在1994/011994/03运行良好,但在1994/02失败了这与闰年有什么关系吗? But more important, how do I get around this problem and make my code work again? 但更重要的是,如何解决这个问题并使我的代码再次运行?

Thanks 谢谢

dtp.parse is filling in the missing day with the current date's day. dtp.parse用当前日期填写缺失的一天。 You ran the code on 2013/01/29 and day 29 does not exist in February (ie 1994/02/29). 您在2013/01/29上运行了代码,并且在2月份(即1994/02/29)不存在第29天。

Use this instead: 请改用:

dtp.parse('1994/01'+'/01')

It will give consistent results (first day of month) regardless of when the code is executed. 无论代码何时执行,它都会给出一致的结果(月的第一天)。

This was a bug in dateutil that has since been fixed. 这是dateutil中的一个错误,此后已被修复。 Version 2.5.0 and higher will no longer have this issue. 版本2.5.0及更高版本将不再出现此问题。

If you must use an earlier version, I think that the "correct" way to handle things is to specify the default parameter: 如果你必须使用早期版本,我认为处理事情的“正确”方法是指定default参数:

from dateutil.parser import parse
from datetime import datetime, date

# First of the current month, at midnight.
default_date = datetime.combine(date.today(), datetime.min.time()).replace(day=1)
dt = parse('1994/01', default=default_date)

This will default to the 1st of the month rather than the current day. 这将默认为当月的第1天而不是当天。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM