Home > Back-end >  python : generate month between date with boundaries
python : generate month between date with boundaries

Time:02-12

let's first put my code

start = datetime(2022,1,5)
end = datetime(2022,5,9)
date_range = (pd.date_range(start, end, freq='MS').to_pydatetime().tolist())
print(test)
if start not in date_range:
    test.insert(0,start)
if end not in date_range:
    test.append(end)

What I am trying to do is to generate a list of month between 2 dates, containing these 2 dates. So if I take 5/1/2021 and 9/5/2022 the list generated should be :

[5/1/2021, 1/2/2021, 1/3/2021, 1/4/2021, 1/5/2021, 9/5/2021]

my issue is pandas date_range return only the month between the date if I choose frequence 'MS', I need to check right after if I have to insert the date or not (basically, if I take 1/1/2021 and 1/5/2021 as start date and end date, they will be here)

Is there a better way to do that in python or I am forced to used these two if after my generation?

Thanks

CodePudding user response:

Let us use Index.union after generating the date_range:

pd.date_range(start, end, freq='MS').union([start, end])

DatetimeIndex(['2022-01-05', '2022-02-01', '2022-03-01', '2022-04-01',
               '2022-05-01', '2022-05-09'],
              dtype='datetime64[ns]', freq=None)
  • Related