获取每月第一天和最后一天
import pandas as pd
beginDate = '2018-08-01'
endDate = '2019-03-31'
date_index = pd.date_range(beginDate, endDate)
days = [pd.Timestamp(x).strftime("%Y-%m-%d") for x in date_index.values]
tmp = []
for index, v in enumerate(days):
if index == len(days) - 1:
tmp.append(days[index])
if index == 0:
tmp.append(days[0])
else:
_ = v.split('-')[2]
if _ == '01':
tmp.append(days[index - 1])
tmp.append(days[index])
print(tmp)
for i in range(len(tmp) // 2):
print(tmp[i * 2], tmp[i * 2 + 1])
获取相隔3个月的开始时间和结束时间
def gen_pd_date_range(start_date, end_date):
s = datetime.datetime.strptime(start_date, "%Y-%m-%d")
e = datetime.datetime.strptime(end_date, "%Y-%m-%d")
delta = (e - s).days
if delta <= 90:
return np.transpose([[start_date], [end_date]])
end_labels = [x[:10] for x in pd.date_range(start_date, end_date,
freq='M').astype(np.str_)][2::3]
start_labels = [start_date] + [str(x + pd.DateOffset(days=1))[:10] for x in
pd.date_range(start_date, end_date, freq='M')][2::3]
if end_labels[-1] == end_date:
return np.transpose([start_labels[:-1], end_labels])
else:
return np.transpose([start_labels, end_labels + [end_date]])
print(gen_pd_date_range('2018-08-01','2019-01-31'))