Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to query using isodate in pymongo

Tags:

python

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?

like image 617
DBWeinstein Avatar asked May 06 '15 20:05

DBWeinstein


2 Answers

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)}})
like image 129
MFB Avatar answered Sep 22 '22 01:09

MFB


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

like image 43
Fred Campos Avatar answered Sep 23 '22 01:09

Fred Campos