14

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?

2
  • 1
    That'd be DB specific. Postgresql for example uses to_char for timestamp formatting, which you could call using sqlalchemy.func. But the (imo) better solution would be to use a JSON serializer that handles datetime objects. Commented Oct 10, 2016 at 14:09
  • you are awesome, thank you very much.my idea go to a wrong way.XD Commented Oct 11, 2016 at 2:03

1 Answer 1

19

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

Sign up to request clarification or add additional context in comments.

3 Comments

This format worked for me 'Dy, DD Mon YYYY HH:MM:SS' in Postgres
Here are the values used by Oracle: techonthenet.com/oracle/functions/to_date.php
Yes, correct format for me func.to_char(User.birthday, 'YYYY-MM-DD')

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.