I found it really hard to predict the results produced by pandas.tseries.offsets
, especially when n==0
. Below is an example with MonthEnd
and MonthBegin
.
import pandas as pd
from pandas.tseries.offsets import MonthEnd, MonthBegin
date_ = pd.to_datetime('20240601')
print(date_ + MonthBegin(0)) # 2024-06-01 00:00:00
print(date_ - MonthBegin(0)) # 2024-06-01 00:00:00
print(date_ + MonthBegin(1)) # 2024-07-01 00:00:00
print(date_ - MonthBegin(1)) # 2024-05-01 00:00:00
print(date_ + MonthEnd(0)) # 2024-06-30 00:00:00
print(date_ - MonthEnd(0)) # 2024-06-30 00:00:00
print(date_ + MonthEnd(1)) # 2024-06-30 00:00:00
print(date_ - MonthEnd(1)) # 2024-05-31 00:00:00
print('n')
date_ = pd.to_datetime('20240615')
print(date_ + MonthBegin(0)) # 2024-07-01 00:00:00
print(date_ - MonthBegin(0)) # 2024-07-01 00:00:00
print(date_ + MonthBegin(1)) # 2024-07-01 00:00:00
print(date_ - MonthBegin(1)) # 2024-06-01 00:00:00
print(date_ + MonthEnd(0)) # 2024-06-30 00:00:00
print(date_ - MonthEnd(0)) # 2024-06-30 00:00:00
print(date_ + MonthEnd(1)) # 2024-06-30 00:00:00
print(date_ - MonthEnd(1)) # 2024-05-31 00:00:00
print('n')
date_ = pd.to_datetime('20240630')
print(date_ + MonthBegin(0)) # 2024-07-01 00:00:00
print(date_ - MonthBegin(0)) # 2024-07-01 00:00:00
print(date_ + MonthBegin(1)) # 2024-07-01 00:00:00
print(date_ - MonthBegin(1)) # 2024-06-01 00:00:00
print(date_ + MonthEnd(0)) # 2024-06-30 00:00:00
print(date_ - MonthEnd(0)) # 2024-06-30 00:00:00
print(date_ + MonthEnd(1)) # 2024-07-31 00:00:00
print(date_ - MonthEnd(1)) # 2024-05-31 00:00:00
If I have to add an if MonthBegin().is_month_end(date_) else ...
before? If there is a way can simplify the logic and make the results predictable? e.g.
for date_ in ['20240601','20240615','20240630']:
# In a word, `n==0` indicates this month, `n==-1` means the previous month and `n==1` means the next month.
date_= pd.to_datetime(date_)
print(date_ + MonthBegin(0)) # == 2024-06-01 00:00:00
print(date_ - MonthBegin(0)) # == 2024-06-01 00:00:00
print(date_ + MonthBegin(1)) # == 2024-07-01 00:00:00
print(date_ - MonthBegin(1)) # == 2024-05-01 00:00:00
print(date_ + MonthEnd(0)) # == 2024-06-30 00:00:00
print(date_ - MonthEnd(0)) # == 2024-06-30 00:00:00
print(date_ + MonthEnd(1)) # == 2024-07-31 00:00:00
print(date_ - MonthEnd(1)) # == 2024-05-31 00:00:00