0

I have tried querying MongoDB through python and get all the objects that were created at a specific date. All the dates in ongare in ISODate format. So they are something like: ISODate("2016-04-19T16:00:00Z").

I want to find all the documents that have as a date, the date "2016-03-19" without considering the time. So what I have done in python is:

date = datetime.datetime(2016,03,19)

startTime = date+datetime.timedelta(seconds=1) //this is: 2016-03-19T00:00:01

endTime = (date + datetime.timedelta(days=1)-datetime.timedelta(seconds=1)) //this is 2016-03-19T23:59:59

cursor= db.collection.find({'data.when.value':'$gte':startTime,'$lte':endTime}}])

I get zero results though, although I have data with this date in my database. Can you please tell me what I'm doing wrong? How can you query just by date and get all documents for this date? I have searched a lot but nothing is working for me.

BanksySan
  • 27,362
  • 33
  • 117
  • 216
suitcase88
  • 21
  • 4
  • could be timezone issue, your query date is naive, i.e. not timezone aware. Try to normalize it to UTC and see what happens – reptilicus Apr 20 '16 at 20:59
  • I did: date = utc.localize(date) but still nothing changed. Now if I print my dates are: 2016-03-19 00:00:01+00:00, 2016-03-19 23:59:59+00:00. Is this what you meant? Thanks! – suitcase88 Apr 20 '16 at 21:23
  • Yeah thats what I was thinking, not sure what else. you sure that startTime < endTime? – reptilicus Apr 20 '16 at 21:49
  • I have printed them and they are: startTime=2016-03-19 00:00:01+00:00 and endTime=2016-03-19 23:59:59+00:00. So I guess I'm fine. :) – suitcase88 Apr 20 '16 at 21:52
  • I found the problem. My original dates shouldn't be of datetime.datetime type but just datetime format. So instead of having date = datetime.datetime(2016,03,19) it should be date=datetime(2016,03,19) and then utc.localize(date). This fixed my problem. Just posted here in case someone else has the same problem with me. – suitcase88 Apr 20 '16 at 22:46
  • Instead of adding and subtracting a 1 second or microsecond or something like that I would use a comparison operator that doesn't include equality (e.g.: `$lt` instead of `$lte`). – pasztorpisti Apr 20 '16 at 22:49
  • @pasztorpisti You are right. I had that in the beginning but then since I was not getting any result I experimented a bit more with the time. However, as it seems the problem is between differentiating the datetime.datetime package in python with the plain datetime. I can't understand why if my query has datetime.datetime type of days it doesn't work and it works if my date is of type datetime. This doesn't make sense to me since if I print the ISODates from mongo inside python, this is of a datetime.datetime type. If someone knows please explain that to me. – suitcase88 Apr 20 '16 at 23:08

0 Answers0