【问题标题】:Type error "must be string, not datetime.datetime"类型错误“必须是字符串,而不是 datetime.datetime”
【发布时间】:2016-11-13 14:26:12
【问题描述】:

我的观点有一些错误,我不知道有什么问题:

from datetime import datetime

for month_dict in finished_by_month:
    month_values.append(month_dict['total'])
    month_date = datetime.strptime(month_dict['month'], '%Y-%m-%d')

当我尝试查看我的模板时出现错误:

"必须是字符串,而不是 datetime.datetime"

我一直在寻找解决方案,但找不到任何东西。也许有人遇到过类似的问题?

【问题讨论】:

  • 您提供的代码不会直接导致错误。您必须提供视图的其余代码以及模板的代码。
  • 看起来像是datetime.datetime,而python需要一个字符串。你还没有发布完整的回溯,我猜month_dict['month']...
  • 搜索"must be string, not datetime.datetime" 会返回很多结果。他们都没有帮助吗?
  • @kaja 发布视图的剩余代码或finished_by_month的值,以便我们提供帮助

标签: python django datetime


【解决方案1】:

假设错误发生在 strptime 函数中,请确保 month_dict['month'] 引用的值是字符串,而不是日期时间格式。当您尝试将字符串转换为特定格式的时间时,编译器期望的值是字符串。

更多时间形式及补充学习详情,请访问https://docs.python.org/2/library/time.html

注意:假设的基础是只有最后一行需要提供字符串格式,而以上所有行都不会抛出这种特定类型的错误。

【讨论】:

    猜你喜欢
    • 2015-12-03
    • 2016-09-02
    • 2013-09-04
    • 2018-04-24
    • 2019-12-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    相关资源
    最近更新 更多