Reputation: 1736
This question has been asked multiple times. But my problem is bit different. I want to create a pandas dataframe with date range which includes start date and end date. The code I'm using is the following:
pd.date_range(start_date, end_date, freq=pd.tseries.offsets.Dateoffset(months=period))
Here period
is dynamic. So, it can be 1, 3, 4, 6 or 12. We also know pd.date_range
does not include end dates. I also don't want to append the end date, as my frequency of period will be affected. So, if my date range is 01-02-2020
and 01-12-2021
. And the frequency is 3 months, then the series will end at 01-11-2021
. If I add the end date at the end, then there's 1 month difference between last date and end date.
DatetimeIndex(['2020-02-01', '2020-05-01', '2020-08-01', '2020-11-01',
'2021-02-01', '2021-05-01', '2021-08-01', '2021-11-01'],
dtype='datetime64[ns]', freq='<DateOffset: months=3>')
My question is how to create the date range series such that it includes extreme values and accommodate the dynamic frequencies.
Thanks!
Upvotes: 2
Views: 1718
Reputation: 3325
If the end date is not provided, it means that the difference between the last provided date and the end date is less than the period. So simply add end_date
to the end of the DatetimeIndex
object returned by date_range
.
start_date=pd.to_datetime("01-02-2020", dayfirst=True)
end_date=pd.to_datetime("01-12-2021", dayfirst=True)
period=3
x=pd.date_range(start_date, end_date, freq=pd.DateOffset(months=period))
if x[len(x)-1].date != end_date.date:
x=np.append(x.date, end_date.date())
print(x)
[datetime.date(2020, 2, 1) datetime.date(2020, 5, 1)
datetime.date(2020, 8, 1) datetime.date(2020, 11, 1)
datetime.date(2021, 2, 1) datetime.date(2021, 5, 1)
datetime.date(2021, 8, 1) datetime.date(2021, 11, 1)
datetime.date(2021, 12, 1)]
Upvotes: 2