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

Python datetime调用报错:‘datetime.datetime’对象无‘datetime’属性

问题原因与解决方案

错误根源

你使用from datetime import datetime导入的是datetime模块中的datetime类,而非整个datetime模块:

  1. 首次报错'datetime.datetime' object has no attribute 'datetime':当前的datetime已经是类本身,无需再通过datetime.datetime调用方法,直接用datetime.now()即可。
  2. 修改后datetime.date(...)仍报错:date是datetime模块下的独立类,你没有导入它,当前的datetime类不存在date属性。

两种解决办法

办法一:补充导入date类

修改导入语句,同时导入datetime类和date类:

from pathlib import Path
from datetime import datetime, date

优化代码(减少重复调用now(),避免时间差):

# 仅调用一次now()获取当前时间
current_dt = datetime.now()
current_year = current_dt.year
current_month = current_dt.month
current_day = current_dt.day

current_week = date(current_year, current_month, current_day).isocalendar()[1]

min_creation_date_to_be_considered_internal = "2023-03-15"
min_creation_date_to_be_considered_external = "2023-03-28"

办法二:导入整个datetime模块

如果习惯datetime.datetime、datetime.date的写法,改为导入整个模块:

from pathlib import Path
import datetime

优化后的运行代码:

current_dt = datetime.datetime.now()
current_year = current_dt.year
current_month = current_dt.month
current_day = current_dt.day

current_week = datetime.date(current_year, current_month, current_day).isocalendar()[1]

min_creation_date_to_be_considered_internal = "2023-03-15"
min_creation_date_to_be_considered_external = "2023-03-28"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 04:22:17