I'm trying to add months to a timestamp object and do not understand the following behaviour:
import pandas as pd
t1 = pd.Timestamp('2020-05-29')+4*pd.DateOffset(months=3)
t2 = pd.Timestamp('2020-05-29')+2*pd.DateOffset(months=6)
I would think that t1 and t2 should be equal (12 months in both cases) but t1 is Timestamp('2021-05-28 00:00:00') and t2 is Timestamp('2021-05-29 00:00:00')
Is this a bug? the correct answer should be t2
Adding DateOffsets expressed in months is a tricky issue.
Actually expression like pd.Timestamp('2020-05-29') + 4 * pd.DateOffset(months=3)
is executed under the hood by adding this offset 4 times.
Run such a code:
tt = pd.Timestamp('2020-05-29')
for i in range(4):
tt += pd.DateOffset(months=3)
print(f'{i}: {tt}')
and you will get:
0: 2020-08-29 00:00:00
1: 2020-11-29 00:00:00
2: 2021-02-28 00:00:00
3: 2021-05-28 00:00:00
Note that when you add 3 months to 2020-11-29 the result is 28-th day of February, since Feruary in 2021 has only 28 days.
The next addition, starting from this date, yields 2021-05-28 (day is also 28).
But when you add DateOffset of 6 months, the situation is as you executed:
tt = pd.Timestamp('2020-05-29')
for i in range(2):
tt += pd.DateOffset(months=6)
print(f'{i}: {tt}')
the result is:
0: 2020-11-29 00:00:00
1: 2021-05-29 00:00:00
Just as intended, since no "stop" on the end of February occurred.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With