Search code examples
pythonpandasdataframedatetimerelativedelta

Python : Subtract 1 month from date


I want subtract 1 month from a date. I'm using relativedelta but this subtract 6 months.

print('the max date : ' , all_data['DT_ANO'].max())
dt_start = all_data['DT_ANO'].max() - relativedelta(month = 1)
print('dt_start : ' , dt_start)

I get this result :

the max date :  2021-08-16 00:00:00
dt_start :  2021-01-16 00:00:00 

instead of :

the max date :  2021-08-16 00:00:00
dt_start :  2021-07-16 00:00:00 

Solution

  • Guessing that relativedelta is a dateutil function, then use

    relativedelta(months=1)
    

    If you use month, year, day, ... the value will be absolute, if you use months, days, years, the value will be relative.