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?
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.
As the documentation says, all() returns the result of the query as a list.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With