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

Python中datetime.strftime报错:descriptor 'strftime'不适用于str对象求助

问题原因与解决方法

你的代码报错核心是调用datetime.strftime时参数顺序错误,同时有更规范的写法可以避免这类问题:

  1. 错误根源
    datetime.strftime作为类方法,要求的参数顺序是:(datetime实例, 格式字符串),但你写的是datetime.strftime("%Y-%m-%d", time_time),把格式字符串放在了第一个参数位置,导致方法接收到的第一个参数是字符串而非datetime对象,直接触发了报错里的类型不匹配问题。

  2. 两种正确写法

  • 推荐:使用datetime实例的strftime方法
    直接在已经解析得到的time_time实例上调用strftime,只需要传入格式字符串即可:
from datetime import datetime

time_string = '2022-08-23 08:48:02'
time_time = datetime.strptime(time_string, '%Y-%m-%d %H:%M:%S')
time_string_again = time_time.strftime("%Y-%m-%d")  # 实例调用
print(time_string_again)  # 输出:2022-08-23
  • 类方法调用(不推荐,易出错)
    如果一定要用类方法datetime.strftime,必须把参数顺序调换,先传datetime实例,再传格式字符串:
time_string_again = datetime.strftime(time_time, "%Y-%m-%d")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:27:22