Filipe Santos
Filipe Santos

Reputation: 401

Print date from MongoDB in Python

I have two objects in the db with diferent dates:

{
"_id" : ObjectId("5addeaf92602ff20497e9406"),
"success" : true,
"timestamp" : 1524477784,
"base" : "EUR",
"date" : "2018-04-22",
"rates" : {
    "AED" : 4.492662,
    "ALL" : 128.39508,
    "AMD" : 586.837094}

and the second one:

{
"_id" : ObjectId("5addb57d0043582d48ba898a"),
"success" : true,
"timestamp" : 1524477784,
"base" : "EUR",
"date" : "2018-04-23",
"rates" : {
    "AED" : 4.492662,
    "ALL" : 128.39508,
    "AMD" : 586.837094}

My python code:

import pymongo

uri = "mongodb://127.0.0.1:27017"
client = pymongo.MongoClient(uri)
database = client['db']
collection = database['currency']

d=(*something I guess*)(input('Insert date: '))
item = collection.find_one({})
data= item['date']['d']
print(data)

What I want is to insert a day or a specific date, and then the program would print that specific day info. In the db the date is in String and I think that I have to convert it. Thanks in advance.

Upvotes: 0

Views: 702

Answers (1)

Abdullah Ahmed Ghaznavi
Abdullah Ahmed Ghaznavi

Reputation: 2099

Well, first of all data= item['date']['d'] this will not gona work because the 2nd [] is used for indexing. And in your case its up to you either you take input same as your string date or convert it into date the take input then put a check on it

For converting string into date do this:

from datetime import date
year, month, day = map(int, (d['date']).split("-"))
required_date = date(year, month, day)
print required_date

Note: assuming that i have your mongo object/dictionary in d

and for second case:

take input from user in the same format in string for e.g:

userinput = str(raw_input('Enter Date: in Format(year, month, day) with seprator "-" e.g: 2018-04-23 \n'))

if userinput == d['date']:
    print 'Correct'

again assuming that d is your mongo object.

Note: Its for exmaple what ever case you are using use then put a if check on it.

Hope it helps you! :)

Upvotes: 1

Related Questions