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

Python使用datetime模块基于已有日期创建新日期时遇类型错误

错误原因与解决方法

错误原因

你在变量赋值时犯了属性调用错误:

  • datetime 对象的日属性是 day(返回整数类型的日期值),而 date 是一个内置方法(调用 until.date() 会返回对应的 date 对象)。
  • 你直接将 date 方法本身赋值给了 day 变量,导致创建新 datetime 对象时,传入的 day 参数是方法对象而非整数,触发了 TypeError。

修正后的代码

import datetime

def difference(current, until):
    # 修正:将 until.date 改为 until.day
    year, month, day = current.year, until.month, until.day
    print("Year:", current.year, "Type:", type(current.year))
    this_year = datetime.datetime(year, month, day)
    return this_year - current

调用示例

可以通过以下方式验证修正后的代码:

current_date = datetime.datetime.now()
target_date = datetime.datetime(2023, 12, 25)
print(difference(current_date, target_date))

运行后会输出两个日期的时间差值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 10:55:20