Search code examples
pythonmongodbpymongobsonpython-datetime

Pymongo query on datetime key returns mongo query operator and huge int


I am writing this query;

end = dt.datetime.today()
start = end - dt.timedelta(7)

query = collection.find({'date' : {'$gt': start, '$lt' : end}},
                       {'_id' : 1, 'name' : 1, 'date_created' : 1})
docs = json.loads(dumps(query))

I am querying using pymongo on a datetime object and converting from bytes to json using bson. What I get back is a document that instead of having a datetime object, it looks like this;

{'_id' : 0, 'name' : 'Brand CN Homepage (Desktop)', 'date' : {'$date' : 1590537600000}}

When I try to convert that huge integer, I get;

OverflowError: Python int too large to convert to C long

the date key, value should look like this;

{'date' : datetime.datetime(2020, 4, 3, 0, 0)}

Is there a way I can get back a datetime object and not a massive integer?


Solution

  • 'date' : {'$date' : 1590537600000}

    This is an extended json representation of a timestamp, documented here. To load extended json, use json_util rather than the standard library json module.