'how to query using isodate in pymongo

I have a mongodb query that works in the mongo shell:

db.collection.find({ created_at:  { $gte : ISODate("2015-03-01T00:00:00.000Z"), $lt : ISODate("2015-03-30T00:00:00.00Z") } })

I'm trying the following pymongo:

test_range = agents.coll.find({ "created_at" :  { "$gte" : "ISODate('2015-03-01T00:00:00.000Z')", "$lt" : "ISODate('2015-03-30T00:00:00.00Z')" } })

and I'm getting SyntaxError: invalid syntax

What the correct way to handle ISODate in pymongo query?



Solution 1:[1]

Dates are stored as ISODates in MongoDB but, when you're using Pymongo, dates are converted to Python Datetime objects. So, using Pymongo, your query should look like this:

test_range = agents.coll.find({ "created_at": {"$gte" : datetime(2015, 3, 1), "$lt": datetime(2015, 3, 30)}})

Solution 2:[2]

Use isoformat(). Example dt = datetime.datetime.now().isoformat().

Solution 3:[3]

Below code is working fine for me

db.yourcollection.find({"createdAt":{"$gte":dateutil.parser.parse(str(date_time_str)),"$lt":dateutil.parser.parse(str(currentdate))},\
"status":"completed"},{"_id":0})

For me if date is not convert into string then a error message is showing "Parser must be a string or character stream, not date"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MFB
Solution 2 Fred Campos
Solution 3 Vijay