Find objects between two dates TinyDB

1.3k Views Asked by At

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.

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

@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

Quick Summary:

  1. My data directly comes from scraping(requests) so i don't wanna rewrite 9-10 key:value pair
  2. I don't wanna store them as datetime object there will be different different endpoints other than searching with date, so i don't wanna return an object like this datetime.datetime(2010, 1, 1, 12, 0)}
1

There are 1 best solutions below

0
On

If you save your dates in TinyDB as time since epoch using:

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()