[英]Find objects between two dates TinyDB
I'm trying tinydb with FastAPI, but i got stuck with dates, Is there a function for finding objects between two dates in TinyDB, i couldn't find any like Pymongo's $gt etc. , i tried something like this but didn't worked out.我正在尝试使用 FastAPI 的 tinydb,但我被日期卡住了,是否有 function 用于在 TinyDB 中查找两个日期之间的对象,我找不到像 Pymongo 的 $gt 之类的东西,我尝试过这样的事情但没有解决了。
class DateTimeSerializer(Serializer):
OBJ_CLASS = datetime # The class this serializer handles
def encode(self, obj):
return obj.strftime('%Y-%m-%dT%H:%M:%S')
def decode(self, s):
return datetime.strptime(s, '%Y-%m-%dT%H:%M:%S')
serialization = SerializationMiddleware()
serialization.register_serializer(DateTimeSerializer(), 'TinyDate')
db = TinyDB("db.json", storage=serialization)
I created a middleware for it from tinydb-serialization but when i search like this我从tinydb-serialization为它创建了一个中间件,但是当我这样搜索时
@app.get("/search")
async def date_get(date: Optional[str] = None,start_at: Optional[str] = None,
end_at: Optional[str] = None, query: Query = Depends()):
if start_at and end_at:
date_db.search((query.date.strptime("%Y/%m/%d") > datetime.strptime(start_at, "%Y/%m/%d")) & (query.date.strptime("%Y/%m/%d") < datetime.strptime(end_at, "%Y/%m/%d")))
Also this pattern throw another exception tinydb:Empty query was evaluated
此模式还会引发另一个异常
tinydb:Empty query was evaluated
Quick Summary :快速总结:
key:value
pairkey:value
对datetime.datetime(2010, 1, 1, 12, 0)}
datetime.datetime(2010, 1, 1, 12, 0)}
If you save your dates in TinyDB as time since epoch using:如果您将 TinyDB 中的日期保存为自纪元以来的时间,请使用:
import datetime
datetime.datetime(year=2022, month=1, day=15).timestamp() //1642204800.0
You can easily query your dates since you are just querying floats您可以轻松查询日期,因为您只是查询浮点数
import datetime
from tinydb import TinyDB, Query
db = TinyDB('db.json')
db.insert_multiple([
{
'id': 1,
'date': datetime.datetime( year=2022, month=1, day=5 ).timestamp()
},
{
'id': 2,
'date': datetime.datetime( year=2022, month=1, day=15 ).timestamp()
}
])
q = Query()
print(db.search(
(q.date < datetime.datetime( year=2022, month=1, day=10 ).timestamp())
&
(q.date > datetime.datetime( year=2022, month=1, day=4 ).timestamp())
))
// prints: [{'id': 1, 'date': 1641340800.0}]
Search query can be shortened to:搜索查询可以缩短为:
datetime.datetime( year=2022, month=1, day=4 ).timestamp() < q.date < datetime.datetime( year=2022, month=1, day=10 ).timestamp()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.