With pd.offsets.WeekOfMonth()
here:
2020-08-10
(i.e.Monday
) offsets to2020-08-12
as expected i.e.Wednesday
of 2nd week (i.e.week=1
)
Trying to understand why doesn't:
2020-08-01
offset to2020-08-05
instead of2020-08-12
.2020-08-21
offset to2020-08-26
instead of2020-09-09
.
[Python 3.9.13; pandas: 2.0.1]
Code:
import pandas as pd
data = pd.Series(
[pd.Timestamp('2020-08-01 01:01:01.001001001'), # Saturday
pd.Timestamp('2020-08-10 01:01:01.001001001'), # Monday
pd.Timestamp('2020-08-21 01:01:01.001001001')]) # Friday
print(data)
print()
Offset:
w = data + pd.offsets.WeekOfMonth(week=1, weekday=2)
print(w)
Output:
0 2020-08-01 01:01:01.001001001 # Saturday
1 2020-08-10 01:01:01.001001001 # Monday
2 2020-08-21 01:01:01.001001001 # Friday
dtype: datetime64[ns]
0 2020-08-12 01:01:01.001001001 # Wednesday
1 2020-08-12 01:01:01.001001001 # Wednesday
2 2020-09-09 01:01:01.001001001 # Wednesday
dtype: datetime64[ns]
Because you use a positive Offset, this will give you the next "second Wednesday of the month".
If you're before one "second Wednesday of a month", this will remain in the same month, otherwise go to the next month's "second Wednesday".
Likewise, using a negative offset: