Pandas date range for a given month in a year

Viewed 831

I need a function which return a date range for a given month and year. Right now i do it for each month manually, e.g.:

mai = pd.date_range(start='05-01-2020', end='05-31-2020') 

Function call should work like that:

range = create_range(month='april', year=2020)

This should deliver a date_range like that:

pd.date_range(start='04-01-2020', end='04-30-2020')
1 Answers

Convert values to datetime and add parameter periods by Timestamp.daysinmonth:

def create_range(month, year):
    d = pd.to_datetime(f'{month} {year}', format='%B %Y')
    return pd.date_range(start = d, periods = d.daysinmonth)    

r = create_range(month='april', year=2020)
print (r)
DatetimeIndex(['2020-04-01', '2020-04-02', '2020-04-03', '2020-04-04',
               '2020-04-05', '2020-04-06', '2020-04-07', '2020-04-08',
               '2020-04-09', '2020-04-10', '2020-04-11', '2020-04-12',
               '2020-04-13', '2020-04-14', '2020-04-15', '2020-04-16',
               '2020-04-17', '2020-04-18', '2020-04-19', '2020-04-20',
               '2020-04-21', '2020-04-22', '2020-04-23', '2020-04-24',
               '2020-04-25', '2020-04-26', '2020-04-27', '2020-04-28',
               '2020-04-29', '2020-04-30'],
              dtype='datetime64[ns]', freq='D')
Related