Generate a list of years with the same month and day

Viewed 38

I'd like to generate a list of '%Y-%m-%d' of the same month and day in different years.

I tried

import pandas as pd
pd.date_range('2014-04-01', '2018-04-01', freq='BYS').strftime("%Y-%m-%d").tolist()

It returns ['2015-01-01', '2016-01-01', '2017-01-02', '2018-01-01']

Expected result ['2014-04-01, '2015-04-01, '2016-04-01', '2017-04-01', '2018-04-01']

1 Answers

Since you want to generate datetime between 2014-04-01 and 2018-04-01 by year, 04-01 is the start day of month. You can use a frequency 12MS where 12M is 12 months and S is month start.

pd.date_range('2014-04-01', '2018-04-01', freq='12MS').strftime("%Y-%m-%d").tolist()

['2014-04-01', '2015-04-01', '2016-04-01', '2017-04-01', '2018-04-01']

If you want to generate datetime between 2014-04-02 and 2018-04-02 by year, you can add an offset to generated date between 2014-04-02 and 2018-04-02.

(pd.date_range('2014-04-01', '2018-04-01', freq='12MS') + pd.DateOffset(days=1)).strftime("%Y-%m-%d").tolist()

['2014-04-02', '2015-04-02', '2016-04-02', '2017-04-02', '2018-04-02']

Reason why pd.date_range('2014-04-02', '2018-04-02', freq='12MS') won't work is that 12MS generates month start between 2014-04-02 and 2018-04-02 that is 2014-05-01 to 2017-05-01.

Related