Query data in MongoDB by date (timestamp) using python

Question:

I am trying to query data by timestamp in a MongoDB using python, but I’m receiving nothing.
I tried to query using other keys (houseColor or houseId ) and it worked, but when I tried to query by timestamp It did not work.

Am I missing something?

My code looks like this:

def filter_by_date(client):
    db_name = client['db']
    collection_name = db_name["collection"]
    data = collection_name.find_one({"timestamp": "2022-01-01T00:00:00.000+00:00"})
    print(data)

The data in MongoDB looks like this:

id: 001
houseColor: "blue"
houseId: "001"
houseName: "sky"
state: "flo"
cost: 100000
timestamp: 2022-01-01T00:00:00.000+00:00
Asked By: Pin90

||

Answers:

The solution was easy, the query using python looks like this:

def filter_by_date(client):
    db_name = client['db']
    collection_name = db_name["collection"]
    query = {'timestamp': datetime(2019, 1, 1, 0, 0)}
    data = collection_name.find_one(query)
    print(data)

So if you want yo query only one date you should have something like this:

query = {'timestamp': datetime(2019, 1, 1, 0, 0)}

If it is a range of dates, the query looks like this:

query = {'timestamp': {"$gte": datetime(2019, 1, 1, 0, 0), "$lt": datetime(2019, 6, 30, 0, 0)}}
Answered By: Pin90
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.