Hi everyone!

In this blog post, I’m going to show you how to use relativedelta from dateutil package to manipulate dates in Python. This is a very handy tool that allows you to add or subtract months, years, weeks, days and other units from a date object. Unlike datetime.timedelta, which only supports days and smaller units, relativedelta can handle more complex calculations that involve different lengths of months or leap years.

Let’s start with a simple example. Suppose you have a date object that represents December 14th, 2022:

from datetime import date
my_date = date(2022, 12, 14)


Now suppose you want to add two months to this date. Unfortunately datetime.timedelta does not allow to use months. However you can use relativedelta:

from datetime import date
from dateutil.relativedelta import relativedelta


## Adding Months to a Particular Date

new_date = my_date + relativedelta(months=2)
If you print new_date, you will get:

>>> print(new_date)
>>> 2023-02-14


As you can see, relativedelta correctly added two months to the original date and returned a new date object. You can also subtract months or other units by using negative values:

## Subtracting Months from a Particular Date

old_date = my_date - relativedelta(months=2)

>>> print(old_date)
>>> 2022-10-14


You can also combine multiple units in one relativedelta object:

## Adding One Year and Three Days to a Particular Date

another_date = my_date + relativedelta(years=1, days=3)

>>> print(another_date)
>>> 2023-12-17


One of the cool features of relativedelta is that it can also replace specific components of a date object with absolute values. For example, if you want to change the day of a given date to 1 (the first day of the month), you can do this:

## Replacing the Day Component with 1

first_day = my_date.replace(day=1)

>>> print(first_day)
>>> 2022-12-01


You can also use weekday parameter to set the weekday of a given date. For example, if you want to find the next Friday after a given date, you can do this:

## Finding the Next Friday After a Given Date

from dateutil.relativedelta import FR # import weekday constants
next_friday = my_date + relativedelta(weekday=FR)

>>> print(next_friday)
>>> 2022-12-16


There are many more parameters and options that relativedelta supports. You can check out the documentation for more details: https://dateutil.readthedocs.io/en/stable/relativedelta.html