Search dates among other dates in Python

Asked

Viewed 155 times

3

Good morning, I have a database on 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 on the 23rd and an end date, on the 25th, and that somehow if possible also search for the information that is between these two dates that in this case is the 24th. I already have Mongo connected with the comic.

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!

1 answer

2


I believe it is enough for you to use the method find, which returns a cursor, not just a record, passing a dictionary as a filter for its date field. For example:

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

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

Operators $gte and $lte are the operators of both equal and equal or greater.

  • In case the user enters the dates as would be?

  • You capture the data and generate the objects datetime.date.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.