Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current date and time from DB using SQLAlchemy

I need to retrieve what's the current date and time for the database I'm connected with SQLAlchemy (not date and time of the machine where I'm running Python code). I've seen this functions, but they don't seem to do what they say:

>>> from sqlalchemy import *
>>> print func.current_date()
CURRENT_DATE
>>> print func.current_timestamp()
CURRENT_TIMESTAMP

Moreover it seems they don't need to be binded to any SQLAlchemy session or engine. It makes no sense...

Thanks!

like image 860
bluish Avatar asked Dec 29 '10 07:12

bluish


1 Answers

I foud the solution: these functions cannot be used in the way I used (print...), but need to be called inside of the code that interacts with the database. For instance:

print select([my_table, func.current_date()]).execute()

or assigned to a field in an insert operation. Accidentally I discovered that exists at least a couple of parameters for these functions:

  • type_ that indicates the type of the value to return, I guess
  • bind that indicates a binding to an SQLAlchemy engine

Two examples of use:

func.current_date(type_=types.Date, bind=engine1)
func.current_timestamp(type_=types.Time, bind=engine2)

Anyway my tests seems to say these parameters are not so important.

like image 76
bluish Avatar answered Sep 27 '22 21:09

bluish