[Answered ]-Pymongo date query in "DD/MM/YYYY" format

2đź‘Ť

âś…

If the dates are stored as strings in the DB, then when you use the operator $gt or $lt, the operation is a string comparison, not a date comparison. Which means that for example: "15/03/2016 < 16/02/2016", because 5 comes before 6 in lexical order.
For the string comparison to work, the dates would need to be stored in a format so that a “smaller” date is always represented as a “smaller” string. For example by using YYYY/MM/DD.

So if you don’t want to do the comparison in python, you could either change the date format, or store the date as a date in DB. But in both cases, this means changing the DB…

If doing in Python is OK, then you can do it like so:

from datetime import datetime

date_format = "%d/%m/%Y"
start_date = datetime.strptime(startDate, date_format)
end_date = datetime.strptime(endDate, date_format)
items = coll.find({})

def compare(c, item):
    item_date = datetime.strptime(item['Date'], date_format)
    if start_date < item_date < end_date:
        return c+1
    else:
        return c

count = reduce(compare, items, 0)
👤Djizeus

Leave a comment