Browse dates and other dates in Python

1

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 enter a start date, in this case day 23 and an end date, day 25, and that somehow if possible also look for the information that is between those two dates that in this case is the day 24. I already have the mongo connected with 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 those who help!

    
asked by anonymous 14.05.2018 / 12:54

1 answer

0

I think you just need to use the find method, which returns a cursor, not just a record, passing a dictionary as a filter of 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 operators $gte and $lte are the operators of greater or equal and less or equal respectively.

    
14.05.2018 / 13:26