0

Is it possible to convert the result of func.now() from sqlalchemy to a string object? Something along the lines of

datetime.datetime.now().strftime('%m/%d/%Y')

I want to use this result in a raw sqlalchemy that updates a datetime column in mysql. This query accepts only string parameters.

1
  • Similar Commented Sep 29, 2023 at 16:31

1 Answer 1

2

Using str(func.now()) returns now() which is the SQL function for using the current timestamp. In other words, if you're constructing a raw query you can pass that in directly and MySQL will automatically fill in the current timestamp. If you want to pass in something along the lines of %m/%d/%Y, then func.now is not the appropriate tool to use.

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

7 Comments

Thanks for the answer. I would like to know if you found this somewhere in the sql alchemy docs? Because I didn't find anything. How did you know applying str will produce 'now()'
I don't know if that specifically is in the docs. But generally you can convert any sort of SQLAlchemy query or function into it's raw SQL equivalent by calling str on it. That's effectively how SQLAlchemy works under the covers.
This inserts a '0000-00-00 00:00:00' in the database. Instead of current time. It doesn't work
What's your full SQL statement?
session.execute(text("UPDATE MoveTable A SET A.city=:city, A.move_date=:move_date"), {'city': NY, 'move_date': str(func.now())}) session.commit()
|

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.