一年中给定月份的熊猫日期范围

时间:2020-06-04 08:39:44

标签: python pandas datetime

我需要一个函数,该函数返回给定月份和年份的日期范围。现在,我每月手动进行一次操作,例如:

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

函数调用应像这样:

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

这应该提供一个类似date_range的内容:

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

1 个答案:

答案 0 :(得分:4)

将值转换为日期时间,并通过Timestamp.daysinmonth添加参数periods

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')