【问题标题】:how to convert a datetime.date object to string in python如何在 python 中将 datetime.date 对象转换为字符串
【发布时间】:2019-12-26 20:29:15
【问题描述】:

当尝试从 mysql 获取日期,并对结果执行 json.dunps 以将其发送回 html 时,出现以下错误:

TypeError: datetime.date(2019, 6, 26) is not JSON serializable

我的数据库结果集看起来像:

[[(B, datetime.date(2019, 6, 26)), (A, datetime.date(2019, 6, 26))], 
 [(A, datetime.date(2019, 6, 26)), (B, '0000-00-00')]]

尝试使用strftimedate object 转换为字符串。不工作。

row_headers = [x[0] for x in cur.description]
for result in rows:
    json_data.append(zip(row_headers, result))

for tup in i:
  core, last_modified = tup
  if last_modified is not None:
    last_modified = datetime.strftime(last_modified, '%d-%m-%M')
    t = datetime.datetime(last_modified)
    t.strftime('%m-%d-%Y')

final_result = {'data': json_data}
    return HttpResponse(json.dumps(final_result), content_type='application/json')

【问题讨论】:

  • 重新组织代码以仅关注特定错误会有所帮助。这里有几个未知数,1)datetime.strftime datetime 中没有这样的方法。 2) i 的值是多少? 3)是行=数据库结果?否则行的值是什么。

标签: python mysql json django


【解决方案1】:

试试这个

return HttpResponse(json.dumps(final_result, default=str), content_type='application/json')

【讨论】:

    猜你喜欢
    • 2012-07-22
    • 2021-01-30
    • 1970-01-01
    • 1970-01-01
    • 2013-10-24
    • 1970-01-01
    • 2023-01-13
    • 2013-07-26
    • 2021-10-05
    相关资源
    最近更新 更多