Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change datetime to string in sqlalchemy query? [duplicate]

this is my code, query Notification.create_time

result = session.query(
        Notification.content, cls.is_read,
        Notification.create_time).join(
        cls, Notification.id == cls.notification).filter(
            and_(cls.user == user_id)).order_by(
                Notification.create_time.desc()).all()

in other place need to json.dumps query result to frontend, datetime format cann't json.dumps, so I want to do like this:

session.query(Notification.create_time.strftime('%Y-%m-%d %H:%M'))

so, how to change datetime to string in sqlalchemy query?

like image 922
max Avatar asked Oct 10 '16 14:10

max


People also ask

What is aliased in SQLAlchemy?

Implementing alias in SQLAlchemy SQL alias is a method of giving a temporary name for a table that is more convenient and readable. SQL alias facilitates a simple name to be used in place of a complex table name when it has to be used multiple times in a query.

What does SQLAlchemy all () return?

As the documentation says, all() returns the result of the query as a list.

What is lazy dynamic SQLAlchemy?

lazy = 'dynamic': When querying with lazy = 'dynamic', however, a separate query gets generated for the related object. If you use the same query as 'select', it will return: You can see that it returns a sqlalchemy object instead of the city objects.


1 Answers

Can use func.to_char() (in postgres, not sure about mysql) to convert a datetime to a string, something like:

from sqlalchemy.sql import func
session.query(func.to_char(Notification.create_time, '%Y-%m-%d %H:%M'))

But the better way it to set up your json serializer to handle things like datetimes, as is described in this answer

like image 97
reptilicus Avatar answered Sep 19 '22 11:09

reptilicus