You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas中提取指定时间段内匹配特定月日的时间戳?

获取日期范围内匹配指定月日的所有日期

我有以下日期变量:

start = '2013-12-03'
end = '2023-07-17'
date = '05-02'

需要获取start和end之间所有月日与date一致的日期,期望输出如下:

DatetimeIndex(['2014-05-02', '2015-05-02', '2016-05-02', '2017-05-02',
               '2018-05-02', '2019-05-02', '2020-05-02', '2021-05-02',
               '2022-05-02', '2023-05-02'],
              dtype='datetime64[ns]', name=0, freq=None)

我当前使用的代码如下:

import pandas as pd 
m, d = map(int, date.split('-'))

idx = pd.date_range(start[:5] + '01-01', end[:5] + '12-31', freq='12M') 
pd.Index(idx.to_frame()[0].add(pd.DateOffset(month=m, day=d))[lambda x: x.between(start, end)])

有没有更简便的实现方式?之前尝试过freq='AS-MAY',但在同月场景下需要额外调整。


简化后的实现方案

基于@Suraj Shourie的回答,我做了简化:

import pandas as pd

start_year = pd.to_datetime(start).year

dates = pd.date_range(f'{start_year}-{date}', end, freq=pd.DateOffset(months=12))
dates[dates >= start]

内容的提问来源于stack exchange,提问作者user17068363

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 02:16:30