如何使用 cur.execute 中的 python return 有效的时间戳值
how to return valid timestamp value using python in cur.execute
在使用 python 日期时间格式读取和 returning sql 查询结果时,时间戳值中包含 T。请大家给点建议。
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)
result_output = [dict((cur.description[i][0], value) for i, value in
enumerate(row)) for row in cur.fetchall()]
return JsonResponse({"result":result_output}, safe=False)
Print result : `[{'tabId': 1, 'tab_int': 100, 'tab_char': 'test5', 'tab_decimal': Decimal('99.54'), 'tab_date': datetime.date(2021, 8, 16), 'tab_timestamp': datetime.datetime(2021, 8, 16, 23, 30, 48)}]`
return 结果
{
"result": [
{
"tabId": 1,
"tab_int": 100,
"tab_char": "test5",
"tab_decimal": "99.54",
"tab_date": "2021-08-16",
"tab_timestamp": "2021-08-16T23:30:48"
}]}
要求的输出是"tab_timestamp": "2021-08-16 23:30:48"
您可以遍历响应数据并重新格式化您想要的类型。要以任何方式格式化 data/datetime 对象,请使用 strftime
(https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes):
from decimal import Decimal
import datetime
data = [{'tabId': 1, 'tab_int': 100, 'tab_char': 'test5',
'tab_decimal': Decimal('99.54'), 'tab_date': datetime.date(2021, 8, 16),
'tab_timestamp': datetime.datetime(2021, 8, 16, 23, 30, 48)}]
for key, value in data[0].items():
if isinstance(value, datetime.datetime):
data[0][key] = data[0][key].strftime("%Y-%m-%d %H:%M:%S")
elif isinstance(value, datetime.date):
data[0][key] = data[0][key].strftime("%Y-%m-%d")
print(data)
在使用 python 日期时间格式读取和 returning sql 查询结果时,时间戳值中包含 T。请大家给点建议。
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)
result_output = [dict((cur.description[i][0], value) for i, value in
enumerate(row)) for row in cur.fetchall()]
return JsonResponse({"result":result_output}, safe=False)
Print result : `[{'tabId': 1, 'tab_int': 100, 'tab_char': 'test5', 'tab_decimal': Decimal('99.54'), 'tab_date': datetime.date(2021, 8, 16), 'tab_timestamp': datetime.datetime(2021, 8, 16, 23, 30, 48)}]`
return 结果
{ "result": [ { "tabId": 1, "tab_int": 100, "tab_char": "test5", "tab_decimal": "99.54", "tab_date": "2021-08-16", "tab_timestamp": "2021-08-16T23:30:48" }]}
要求的输出是"tab_timestamp": "2021-08-16 23:30:48"
您可以遍历响应数据并重新格式化您想要的类型。要以任何方式格式化 data/datetime 对象,请使用 strftime
(https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes):
from decimal import Decimal
import datetime
data = [{'tabId': 1, 'tab_int': 100, 'tab_char': 'test5',
'tab_decimal': Decimal('99.54'), 'tab_date': datetime.date(2021, 8, 16),
'tab_timestamp': datetime.datetime(2021, 8, 16, 23, 30, 48)}]
for key, value in data[0].items():
if isinstance(value, datetime.datetime):
data[0][key] = data[0][key].strftime("%Y-%m-%d %H:%M:%S")
elif isinstance(value, datetime.date):
data[0][key] = data[0][key].strftime("%Y-%m-%d")
print(data)