xin.chen
xin.chen

Reputation: 986

python django pymysql query formatting datetime output?

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

Upvotes: 0

Views: 253

Answers (1)

yvesonline
yvesonline

Reputation: 4837

Assuming you're using MySQL you can format ctime using date_format in your select statement:

sql = "select congestion_level, arrival_flow, date_format(ctime, '%Y-%m-%d %H:%M:%S') from target"

Upvotes: 1

Related Questions