Python Pandas Datetime:如何将财年与财月转换为公历日期
财年财月转公历日期的实现方案
问题背景
现有如下包含ID、财年(Financial_Year)、财月(Financial_Month)的DataFrame,每个ID对应多条记录:
ID Financial_Year Financial_Month 1 2021 1 1 2022 2 2 2021 3 2 2023 12
需将财年与财月转换为公历日期,转换规则为:财年周期为当年7月至次年6月(例如FY2022对应2021年7月为财年第1月,2022年6月为财年第12月),预期输出如下:
ID Financial_Year Financial_Month Calendar_date 1 2021 1 01-07-2021 1 2022 2 01-08-2022 2 2021 3 01-09-2021 2 2023 12 01-06-2023
实现代码
使用Pandas即可完成转换,核心逻辑是通过财月推导公历的年、月,再生成标准日期:
import pandas as pd # 初始化原始数据 df = pd.DataFrame({ 'ID': [1, 1, 2, 2], 'Financial_Year': [2021, 2022, 2021, 2023], 'Financial_Month': [1, 2, 3, 12] }) # 计算公历月份和年份 df['temp_month'] = df['Financial_Month'] + 6 df['temp_year'] = df['Financial_Year'] # 处理月份超过12的情况:年份+1,月份减12 over_12_mask = df['temp_month'] > 12 df.loc[over_12_mask, 'temp_year'] += 1 df.loc[over_12_mask, 'temp_month'] -= 12 # 生成格式化的公历日期字符串(固定每月1号) df['Calendar_date'] = pd.to_datetime( df[['temp_year', 'temp_month']].assign(day=1) ).dt.strftime('%d-%m-%Y') # 清理临时计算列 df = df.drop(['temp_year', 'temp_month'], axis=1) # 输出结果 print(df)
逻辑说明
- 财年第N月对应公历的初始月份为
N+6,比如财月1对应公历7月(1+6=7),财月12对应公历18月 - 当计算出的月份>12时,说明进入了下一个公历年份,此时年份加1,月份减去12(比如18月→次年6月)
- 用
pd.to_datetime将年、月、固定日(1号)转换为日期对象,再通过strftime格式化为dd-mm-yyyy的字符串 - 最后删除临时列,得到目标结构的DataFrame
内容的提问来源于stack exchange,提问作者technical
相关产品推荐
相关产品推荐

