How to change date and time to string in sqlalchemy query?

this is my code request 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() 

elsewhere, you need to execute json.dumps the query result for frontend, the datetime format can'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 date and time to string in sqlalchemy query?

+5
source share
1 answer

May use func.to_char() (in postgres, not sure about mysql) to convert date and time to string, something like:

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

But the best way to configure your json serializer to handle things like datetimes as described in this answer

+4
source

Source: https://habr.com/ru/post/1257966/


All Articles