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

后端 未结 2 1833
后悔当初
后悔当初 2021-01-04 19:55

I have a the following code that runs fine with input format like {Year}/{Month} except when it comes to 1994/02

Here is the sample code

2条回答
  •  孤街浪徒
    2021-01-04 20:35

    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.

提交回复
热议问题