0

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

2
  • I don't understand: you want the field ctime as string or as datetime object? Because it looks like it already is a string. Commented Mar 23, 2021 at 11:29
  • 1
    So you're on MySQL? Then you can format in the select, i.e. select name, congestion_level, arrival_flow, date_format(ctime, '%Y-%m-%d %H:%M:%S') from target. Commented Mar 23, 2021 at 11:30

1 Answer 1

1

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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.