python-dateutilpython-relativedelta

dateutil.relativedelta handles years incorrectly


There's something wrong with adding years:

from datetime import datetime
from dateutil.relativedelta import relativedelta

if __name__ == '__main__':
    date = datetime.today().date()
    print(date)
    print(date + relativedelta(year=1))

### 2022-07-27
### 0001-07-27 – why!?

Could anyone explain that?


Solution

  • The issue you are having is that year (singular) sets the year of whatever it is added to, whereas years (plural) represents an offset in years. See the documentation, which has a whole section on the difference.