Python执行cur.execute查询MySQL时如何返回不带T的合规时间戳值
问题原因
返回结果中的T是因为JsonResponse默认使用的JSON序列化规则会将datetime.datetime类型的对象转换为ISO 8601标准格式字符串,该格式默认使用T分隔日期和时间部分。
解决方案
方案1:遍历结果集时直接格式化时间字段
在生成结果集的过程中判断字段值类型,遇到时间类型就手动转为目标格式,仅对当前接口生效,灵活度高,修改后代码如下:
import datetime from decimal import Decimal from django.http import JsonResponse import mysql.connector con = mysql.connector.connect(host=host, user=username, password=password, database=db_name,port=port) cur = con.cursor() sqlquery = "select * from testtable" cur.execute(sqlquery) # 自定义值转换逻辑 def format_value(value): if isinstance(value, datetime.datetime): return value.strftime("%Y-%m-%d %H:%M:%S") elif isinstance(value, datetime.date): return value.strftime("%Y-%m-%d") elif isinstance(value, Decimal): return str(value) # 若需要数值类型可改为float(value) return value result_output = [ dict((cur.description[i][0], format_value(value)) for i, value in enumerate(row)) for row in cur.fetchall() ] return JsonResponse({"result":result_output}, safe=False)
方案2:自定义全局JSON序列化器(Django框架适用)
如果项目多个接口都需要统一时间格式,可自定义JSON编码器实现一次修改全局生效:
- 先定义自定义编码器类
import json import datetime from decimal import Decimal class CustomJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime.datetime): return obj.strftime("%Y-%m-%d %H:%M:%S") elif isinstance(obj, datetime.date): return obj.strftime("%Y-%m-%d") elif isinstance(obj, Decimal): return str(obj) return super().default(obj)
- 调用
JsonResponse时指定编码器即可
return JsonResponse({"result":result_output}, safe=False, cls=CustomJSONEncoder)
如需全局生效可在Django的settings.py中配置JSON_ENCODER = "你的模块路径.CustomJSONEncoder",后续所有JsonResponse都会默认使用该序列化规则。
方案3:SQL查询阶段直接格式化时间字段
使用数据库自带的日期格式化函数,查询时直接返回符合要求的字符串,性能最优,以MySQL为例修改SQL语句:
select tabId, tab_int, tab_char, tab_decimal, tab_date, DATE_FORMAT(tab_timestamp, '%Y-%m-%d %H:%i:%s') as tab_timestamp from testtable
内容的提问来源于stack exchange,提问作者sugnez
相关产品推荐
相关产品推荐

