pythonpython-dateutilrelativedelta

Python dateutils relativedelta incorrect result when starting with 30 day month


I'm trying to create some date recurrence rules. Based on the issues with dateutil noted here and here I am trying to use relativedelta rather than rrule. However, I am encountering a silly problem that is stumping me and which is illustrated with the following minimal example. Consider this:

MONTH = relativedelta(months=+1)
print(first_date + MONTH, first_date + 2*MONTH)

When first_date is the last day in a month with 31 days, such as 05/31/2007, the code yield the correct two dates: June 30th and July 31st.

But, when first_date is the last day in a month with 30 days, such as 04/30/2007, the code yields : May 30th and June 30th. What it should have given is May 31st and June 30th.

Any ideas how I can overcome this issue?


Solution

  • The reason this doesn't work is because you can't specify you're taking the last day of a month, just the 31st, 30th of 28th. The only reason this works for months with 31 days is simply because that's a special case that must be handled by relativedelta

    By adding and subtracting one day, the problem gets resolved:

    from datetime import date
    from dateutil.relativedelta import relativedelta
    
    DAY = relativedelta(days=+1)
    MONTH = relativedelta(months=+1)
    
    first_date = date(2007, 4, 30) + DAY
    print(first_date + MONTH - DAY, first_date + 2*MONTH - DAY)
    

    Output:

    2007-05-31 2007-06-30