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

Python中将日期转财年代码报AttributeError,求bug排查

问题分析与修复

核心错误点

  • 缺失datetime模块导入:代码中调用datetime.datetime.strptime但未导入datetime模块,会触发NameError。
  • 错误调用FiscalYear类:fiscalyear.FiscalYear.New_CF_Date.fiscal_year是错误语法,FiscalYear类需要接收日期对象作为参数实例化,不能直接通过类访问自定义变量。

修复后的完整代码

!pip install fiscalyear
import fiscalyear
import datetime  # 补充导入datetime模块

fiscalyear.START_MONTH = 9

New_CF_Date='5/10/2017 12:00:00 AM'
blank_pos=New_CF_Date.index(' 12:00:00 AM')
New_CF_Date_0=New_CF_Date[:blank_pos]
format = "%m/%d/%Y"
New_CF_Date = datetime.datetime.strptime(New_CF_Date_0, format)

# 修复:将datetime对象传入FiscalYear构造函数,再获取财年属性
intTargetFiscalYear = fiscalyear.FiscalYear(New_CF_Date).fiscal_year

print(intTargetFiscalYear)

简洁优化版

可以直接使用FiscalDate类简化日期处理流程:

!pip install fiscalyear
import fiscalyear

fiscalyear.START_MONTH = 9

New_CF_Date='5/10/2017 12:00:00 AM'
# 直接提取日期部分并转换为FiscalDate对象
fiscal_date = fiscalyear.FiscalDate.from_string(New_CF_Date.split(' ')[0], "%m/%d/%Y")
print(fiscal_date.fiscal_year)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 05:31:08