如何使用SQLAlchemy从DB获取当前日期和时间

时间:2022-10-03 21:53:42

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:

我需要检索我与SQLAlchemy连接的数据库的当前日期和时间(不是我正在运行Python代码的机器的日期和时间)。我已经看过这个功能了,但他们似乎没有做他们说的话:

>>> 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...

此外,它们似乎不需要绑定到任何SQLAlchemy会话或引擎。这个不成立...

Thanks!

谢谢!

1 个解决方案

#1


5  

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 ...),但需要在与数据库交互的代码中调用。例如:

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
  • type_,表示要返回的值的类型,我想
  • bind that indicates a binding to an SQLAlchemy engine
  • bind表示绑定到SQLAlchemy引擎

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.

无论如何,我的测试似乎说这些参数并不那么重要。

#1


5  

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 ...),但需要在与数据库交互的代码中调用。例如:

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
  • type_,表示要返回的值的类型,我想
  • bind that indicates a binding to an SQLAlchemy engine
  • bind表示绑定到SQLAlchemy引擎

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.

无论如何,我的测试似乎说这些参数并不那么重要。