python 获取过去一年的月初和月末日期

import datetime
import pandas as pd
from dateutil.relativedelta import relativedelta

def get_history_date():
end_date = datetime.date.today()
start_date = end_date - relativedelta(years=1)
date_index = pd.date_range(start_date, end_date)
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])
return [[tmp[i * 2], tmp[i * 2 + 1]] for i in range(len(tmp) // 2)][1:]

print(get_history_date())

”“”
[[‘2022-12-01’, ‘2022-12-31’],
[‘2023-01-01’, ‘2023-01-31’],
[‘2023-02-01’, ‘2023-02-28’],
[‘2023-03-01’, ‘2023-03-31’],
[‘2023-04-01’, ‘2023-04-30’],
[‘2023-05-01’, ‘2023-05-31’],
[‘2023-06-01’, ‘2023-06-30’],
[‘2023-07-01’, ‘2023-07-31’],
[‘2023-08-01’, ‘2023-08-31’],
[‘2023-09-01’, ‘2023-09-30’],
[‘2023-10-01’, ‘2023-10-31’],
[‘2023-11-01’, ‘2023-11-21’]]
“”“

你可能感兴趣的:(python)