Pandas使用频率偏移量计算日期时如何得到对应日而非月末
Pandas 日历对日偏移计算实现方案
问题原因
pandas 内置的pd.tseries.frequencies.to_offset方法中,M、Y这类单位默认是锚定到周期末尾的偏移规则,比如1M偏移会对齐到月份最后一天,所以才会出现2021-08-25减1M得到2021-07-31的结果,不符合「对日偏移一个月」的需求。
解决方案
使用pd.DateOffset实现按日历的年月日对日偏移,支持用户输入的1D、10M、1Y格式偏移量的通用实现如下:
基础示例(单场景调用)
import pandas as pd # 2021-08-25 偏移1个月 res = pd.Timestamp('2021-08-25') - pd.DateOffset(months=1) print(res) # 输出:2021-07-25 00:00:00
通用封装(支持任意格式偏移量输入)
def calc_offset_date(base_date: pd.Timestamp, offset_str: str) -> pd.Timestamp: # 拆分偏移量的数值与单位 num_part = ''.join(filter(str.isdigit, offset_str)) unit_part = ''.join(filter(lambda x: not x.isdigit(), offset_str)).strip().upper() # 单位映射 unit_mapping = { 'D': 'days', 'M': 'months', 'Y': 'years' } if unit_part not in unit_mapping: raise ValueError(f"不支持的偏移单位:{unit_part},当前仅支持D/天、M/月、Y/年") # 计算偏移后日期 return base_date - pd.DateOffset(**{unit_mapping[unit_part]: int(num_part)})
测试验证
# 测试1:1M偏移 print(calc_offset_date(pd.Timestamp('2021-08-25'), '1M')) # 输出:2021-07-25 00:00:00 # 测试2:1Y偏移 print(calc_offset_date(pd.Timestamp('2021-08-25'), '1Y')) # 输出:2020-08-25 00:00:00 # 测试3:10D偏移 print(calc_offset_date(pd.Timestamp('2021-08-25'), '10D')) # 输出:2021-08-15 00:00:00 # 测试4:边界日期(月末偏移) print(calc_offset_date(pd.Timestamp('2023-03-31'), '1M')) # 输出:2023-02-28 00:00:00
边界说明
如果偏移后对应月份不存在目标日(比如3月31日减1个月,2月没有31日),DateOffset会自动对齐到当月最后一天,符合常规的日期偏移认知。
内容的提问来源于stack exchange,提问作者Lopez
相关产品推荐
相关产品推荐

