What is the difference between relativedelta() and DateOffset()

280 Views Asked by At

I am having trouble understanding the differences between the relativedelta() function from the dateutil module and the DateOffset() function from Pandas. To me their syntax and outcomes are the same. For example:

import pandas as pd
from dateutil.relativedelta import relativedelta

current_date = pd.to_datetime('2023-09-10')

print('current_date + relativedelta(months = 1)')
print('current_date + pd.DateOffset(months = 1)')

Results:

2023-10-10 00:00:00

2023-10-10 00:00:00

2

There are 2 best solutions below

0
jtobelem On

both functions do the same thing. The pandas function can be used for vectorized operations like :

df = pd.DataFrame(pd.date_range(start='2022-01-01', end='2022-01-31'), columns=['date'])

And you can add the offset to all values :

df['date'] + pd.DateOffset(months = 1)
0
Henrik On

DateOffset takes care of daylight saving, Timedelta does not.

import datetime as dt

import pandas as pd
import pytz
from dateutil.relativedelta import relativedelta


t = pytz.timezone("Europe/Amsterdam").localize(dt.datetime(2000, 1, 1))
print(f"start: {t}")
print(f"{t + pd.DateOffset(months=3)} using offset")
print(f"{t + relativedelta(months=3)} using relativedelta")

gives

start: 2000-01-01 00:00:00+01:00
2000-04-01 00:00:00+02:00 using offset
2000-04-01 00:00:00+01:00 using relativedelta