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

此生再无相见时 提交于 2019-11-30 19:14:29

dtp.parse is filling in the missing day with the current date's day. You ran the code on 2013/01/29 and day 29 does not exist in February (i.e. 1994/02/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. Version 2.5.0 and higher will no longer have this issue.

If you must use an earlier version, I think that the "correct" way to handle things is to specify the default parameter:

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!