pandas python从日期范围中获取季度日期

yrdbyhpb  于 2022-12-09  发布在  Python
关注(0)|答案(3)|浏览(173)

python从日期范围中获取季度日期
例如:

start date = 01/04/2020
end date = 01/04/2021

在这里我需要从这个日期范围中得到第四纪的日期。

unguejic

unguejic1#

试试看:

start_date = "01/04/2020"
end_date = "01/04/2021"
pd.date_range(start_date, end_date, freq='Q')

DatetimeIndex(['2020-03-31', '2020-06-30', '2020-09-30', '2020-12-31'], dtype='datetime64[ns]', freq='Q-DEC')
jhiyze9q

jhiyze9q2#

pd.date_range(start date, end date, freq='3m').to_period('Q')
ymdaylpp

ymdaylpp3#

纯Python皮:

import datetime

start_date_str = "01/04/2020"
end_date_str = "01/04/2021"

start_date = datetime.datetime.strptime(start_date_str, "%d/%m/%Y").date()
end_date = datetime.datetime.strptime(end_date_str, "%d/%m/%Y").date()

print(f"Quarters within {start_date_str} and {end_date_str}:")
start_of_quarter = start_date
while True:
    far_future = start_of_quarter + datetime.timedelta(days=93)
    start_of_next_quarter = far_future.replace(day=1)
    end_of_quarter = start_of_next_quarter - datetime.timedelta(days=1)
    if end_of_quarter > end_date:
        break
    print(f"\t{start_of_quarter:%d/%m/%Y} - {end_of_quarter:%d/%m/%Y}")
    start_of_quarter = start_of_next_quarter

相关问题