Reputation: 581
I want to generate the following Dataframe with Pandas:
print(last_three_months)
TimePeriod.Start TimePeriod.End
1 2021-03-01 2021-04-01
2 2021-04-01 2021-05-01
3 2021-05-01 2021-05-31
I can generate the first and last day of a certain month with the following code:
from datetime import datetime
first_day_month = datetime(2021, 3, 1)
last_day_month = firstday_month + pd.offsets.MonthEnd(1)
Is there a way to generate this dataframe without having to define each date one by one with long-winded code such as
month_x = int(pd.to_datetime("today").strftime("%m"))
monthx_1 = int(pd.to_datetime("today").strftime("%m"))-1
...
and assigning each resulting value to a df block one by one?
I'm guessing there's an easier way to do this.
Upvotes: 0
Views: 399
Reputation: 23146
You can use pd.date_range
and generate the DataFrame as follows:
start = pd.Timestamp(year=2021, month=3, day=1)
df = pd.DataFrame({"Start": pd.date_range(start, periods=3, freq="MS"),
"End": pd.date_range(start, periods=3, freq="M")})
df
is now:
Start End
0 2021-03-01 2021-03-31
1 2021-04-01 2021-04-30
2 2021-05-01 2021-05-31
Upvotes: 2