Searching for dates among other dates in Python

Question:

Good morning, I have a database in Mongo DB like this:

{
"_id" : ObjectId("5addb57d0043582d48ba898a"),
"base" : "EUR",
"date" : "2018-04-23",
"rates" : {
    "BRL" : 4.175076
}

{
"_id" : ObjectId("5addb57d0043582d48ba898a"),
"base" : "EUR",
"date" : "2018-04-24",
"rates" : {
    "BRL" : 4.185076
}

    {
"_id" : ObjectId("5addb57d0043582d48ba898a"),
"base" : "EUR",
"date" : "2018-04-25",
"rates" : {
    "BRL" : 4.205076
}

And in Python I would like to insert a start date, in this case the 23rd and an end date, the 25th, and that somehow if possible also look for the information that is between these two dates, which in this case is the 24th. I already have mongo connected with the bd.

import pymongo

#conectar à bd
uri = "mongodb://127.0.0.1:27017"
client = pymongo.MongoClient(uri)
database = client['db']
collection = database['currency']
collection2 = database['countries']

#Encontar dados na bd
p = str(input('Insira o país: '))
d = input('Insira a data no formato (yyyy-mm-dd): ')
item = collection.find_one({"date" : d})

if p == 'Brasil':
 d = collection.find_one({})
 item = collection2.find_one({"Pais": p})
 aj = item['ajudacusto']
 primeiramoeda = item['MoedaLocal']
 item2 = collection.find_one({})
 segundamoeda = item2['rates']['EUR']
 moedafinal = item2['rates'][primeiramoeda]
 res = (segundamoeda / moedafinal)
 res2 = res * aj
 print('Você ficou {} dias, que em ajuda de custo dará {:.2f}€'.format(dias, res2))

Thanks to anyone who helps!

Answer:

I believe that you just use the find method, which returns a cursor, not just a record, passing a dictionary as a filter for your date field. For example:

inicio = datetime.date(2018, 4, 23)
final = datetime.date(2018, 4, 25)

collection.find({
    'date': {
        '$gte': inicio,
        '$lte': final
    }
})

The $gte and $lte operators are greater than or equal to and less than or equal to, respectively.

Scroll to Top