Search code examples
python-3.xpython-dateutil

python relativedelta not working for months of 31


I want to create quarter dates based on end date of previous quarter. meaning that, for each quarter's end date i've to subtract 3 months to calculate start date of quarter and end date of previous quarter.

Problem is , when I do

ref_date - relativedelta(months=+3)

and ref_date is 30th june, it returns march 30th while it should return march 31st. is there any solution to it ?


Solution

  • Assuming you are working with datetime.date objects.

    You can check how many days are a in month of a year with calendar.monthrange and use that as your date instead of just the negation result. When you got that figured out you have to create a new datetime.date because its attributes are not writable:

    import datetime
    from dateutil.relativedelta import relativedelta
    import calendar
    
    ref_date = datetime.date(2022, 6, 30)
    end_date = ref_date - relativedelta(months=3)
    n_days = calendar.monthrange(end_date.year, end_date.month)[1]
    end_date = datetime.date(end_date.year, end_date.month, n_days)
    print(end_date)
    

    Out:

    2022-03-31