python3.8 sql
sql="select * from target"
def dictfetchall(cursor):
"Return all rows from a cursor as a dict"
columns = [col[0] for col in cursor.description]
return [
dict(zip(columns, row))
for row in cursor.fetchall()
]
with connection.cursor() as cursor:
cursor.execute(sql_query)
data = dictfetchall(cursor)
return data
data output is
[{
"name": "tom",
"congestion_level": null,
"arrival_flow": 15.0,
"ctime": "2020-04-11T12:00:00"
},
{
"name": "jack",
"congestion_level": null,
"arrival_flow": 25.0,
"ctime": "2020-04-11T12:00:00"
}]
ctime this fields has T,if I remove T I need run following code:
def datetime_to_str(old_dict_list):
for old_dict in old_dict_list:
for x, y in old_dict.items():
if isinstance(y, datetime.datetime):
old_dict[x] = datetime.datetime.strftime(y, '%Y-%m-%d %H:%M:%S')
return list(old_dict_list)
I think my method is not pythonic,I don’t want to use django orm because of the complex sql statement
ctimeas string or as datetime object? Because it looks like it already is a string.select, i.e.select name, congestion_level, arrival_flow, date_format(ctime, '%Y-%m-%d %H:%M:%S') from target.