这是一个使用“业务”日过滤和自定义周掩码的numpy解决方案:
>>> all_days = np.arange('1970-02-05', '1970-05-08', dtype='M8[D]')
>>> week_start_end = all_days[np.is_busday(all_days, weekmask='Mon Sun')]
>>> week_start_end
array(['1970-02-08', '1970-02-09', '1970-02-15', '1970-02-16',
'1970-02-22', '1970-02-23', '1970-03-01', '1970-03-02',
'1970-03-08', '1970-03-09', '1970-03-15', '1970-03-16',
'1970-03-22', '1970-03-23', '1970-03-29', '1970-03-30',
'1970-04-05', '1970-04-06', '1970-04-12', '1970-04-13',
'1970-04-19', '1970-04-20', '1970-04-26', '1970-04-27',
'1970-05-03', '1970-05-04'], dtype='datetime64[D]')
这仅适用于数周.对于其他单位:
>>> def first_last_range(start, stop, step='M', resolution='D'):
... large = np.arange(start, stop, dtype=f'M8[{step}]')
... first = large.astype(f'M8[{resolution}]')
... last = (large + np.timedelta64(1, step)).astype(f'M8[{resolution}]') - np.timedelta64(1, resolution)
... full = np.c_[first, last].ravel()
... return full[full[0] < np.datetime64(start) : len(full) - (full[-1] > np.datetime64(stop))]
...
>>>
>>> first_last_range('1970-02-05', '1970-05-08')
array(['1970-02-28', '1970-03-01', '1970-03-31', '1970-04-01',
'1970-04-30'], dtype='datetime64[D]')
请注意,您可能想使端点语义适应您的需求.