Python/Sqlalchemy/Sqlite - 如何在条件下添加日期时间字段和整数秒(timedelta)?
我有一个 sqlalchemy/sqlite 表:
class MyTable(Base):
__tablename__ = 'mytable'
...
field_dt = Column(DateTime)
field_int = Column(Integer, default=0)
现在我想构造 where 条件,在其中我想检查 field_dt + field_int (秒) <= utc_now。 类似于:select(MyTable).where(?)
。
如果没有 sqlalchemy/sqlite,我会构造如下条件:
import datetime as dt
utc_now = dt.datetime(2022,3,2,1,0,10)
field_dt = dt.datetime(2022,3,1,1,0,5)
field_int = 60
print(f" utc_now = {utc_now.isoformat()}")
print(f" field_dt = {field_dt.isoformat()}")
print(f"field_int = {field_int}")
if field_dt + dt.timedelta(seconds=field_int) < utc_now:
print('it is less than utc_now')
输出:
utc_now = 2022-03-02T01:00:10
field_dt = 2022-03-01T01:00:05
field_int = 60
it is less than utc_now
如何对 sqlalchemy/sqlite 执行相同操作
I have a sqlalchemy/sqlite table:
class MyTable(Base):
__tablename__ = 'mytable'
...
field_dt = Column(DateTime)
field_int = Column(Integer, default=0)
Now I would like to construct the where condition in which I want to check whether field_dt + field_int (seconds) <= utc_now.
Something like: select(MyTable).where(?)
.
With no sqlalchemy/sqlite I would construct condition like this:
import datetime as dt
utc_now = dt.datetime(2022,3,2,1,0,10)
field_dt = dt.datetime(2022,3,1,1,0,5)
field_int = 60
print(f" utc_now = {utc_now.isoformat()}")
print(f" field_dt = {field_dt.isoformat()}")
print(f"field_int = {field_int}")
if field_dt + dt.timedelta(seconds=field_int) < utc_now:
print('it is less than utc_now')
Output:
utc_now = 2022-03-02T01:00:10
field_dt = 2022-03-01T01:00:05
field_int = 60
it is less than utc_now
How to do the same with sqlalchemy/sqlite
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
SQLite 3.38.0 实现了一个
unixepoch
函数,可以将日期时间转换为 Unix 时间戳,因此理论上我们可以这样做,但是 3.38.0 于 2022 年 2 月 22 日发布,所以在编写它时可能不会广泛分布。
如果
unixepoch
不可用,我们可以使用SQLite的datetime
函数来构造一个新的datetime
。 SQL 看起来像这样:SQLAlchemy 等价的是:
如果
field_dt
被索引,请考虑将修饰符移动到不等式的 RHS:可能值得考虑将日期时间存储为 Unix 时间戳以简化查询。
SQLite 日期函数文档位于此处。
SQLite 3.38.0 implements a
unixepoch
function that can convert a datetime to a Unix timestamp, so in theory we could dohowever 3.38.0 was released on 2022-02-22 so at the time of writing it may not be widely distributed.
If
unixepoch
is not available we can use SQLite'sdatetime
function to construct a newdatetime
. The SQL would look something like this:the SQLAlchemy equivalent is:
If
field_dt
is indexed, consider moving the modifier to the RHS of the inequality:It may be worth considering storing the datetime as a Unix timestamp to simplify the query.
The SQLite date functions documentation is here.