SQLAlchemy中使用日期和间隔的正确方法是什么?

huangapple go评论79阅读模式
英文:

Whats the proper way to use date and interval in SQLAlchemy?

问题

date_filter = (datetime.today() - timedelta(days=7)).strftime('%Y-%m-%d')
.filter(DayManifestBatch.manifest_date >= cast(date_filter, DATE))
英文:

I need to implement this filter in SQLalchemy, with a MySQL database

dmb.manifest_date >= (CURDATE() - interval 7 day)

What I did is

date_filter=(datetime.today()-timedelta(days=7)).strftime('%Y-%m-%d')
.filter(DayManifestBatch.manifest_date>= cast(date_filter,DATE))

I imported DATE and cast from SQLALchemy. Also tried with just the string date and datetime format but I always get this error

sqlalchemy.exc.ArgumentError: SQL expression object expected, got object of type <class 'flask_sqlalchemy.model.DefaultMeta'> instead

</details>


# 答案1
**得分**: 0

也许有更好的方法,但你可以使用:

```python
from sqlalchemy import text

.filter(DayManifestBatch.manifest_date >= text('CURDATE() - INTERVAL 7 DAY'))
英文:

There is probably a better way but you can use:

from sqlalchemy import text

.filter(DayManifestBatch.manifest_date &gt;= text(&#39;CURDATE() - INTERVAL 7 DAY&#39;))

huangapple
  • 本文由 发表于 2023年3月15日 21:08:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75745180.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定