Reputation: 85
I have this code in Python:
import datetime
import re
import pymongo
from datetime import timedelta, date
def daterange(d, d1):
for n in range(int ((d1 - d).days)):
yield d + timedelta(n)
#conect to db
uri = "mongodb://127.0.0.1:27017"
client = pymongo.MongoClient(uri)
database = client['db']
collection = database['currency']
d = input('Insert beginning date (yyyy-mm-dd): ')
d1 = input('Insert end date (yyyy-mm-dd): ')
#search db
item = collection.find_one({"date" : d})
item1 = collection.find_one({"date" : d1})
datas = item['date']
datas1 = item1['date']
#convert string to object
dataObject = datetime.datetime.strptime(datas, "%Y-%m-%d")
dataObject1 = datetime.datetime.strptime(datas1, "%Y-%m-%d")
#range
mylist = []
for single_date in daterange(dataObject, dataObject1):
mylist.append(single_date.strftime("%Y-%m-%d"))
print(single_date.strftime("%Y-%m-%d"))
print(mylist)
item = collection.find_one({"date" : mylist[0]})
print(item)
If a user inserts a beginning date like 2018-05-07 and an end date like 2018-05-11 it will print:
2018-05-07
2018-05-08
2018-05-09
2018-05-10
In this case it will only print until the 10th day, how should I do to print also the end date (2018-05-11)?
Upvotes: 0
Views: 863
Reputation: 94
There are many solutions to your question, however, I believe the easiest would be to adjust the daterange(d, d1)
function, by simply adding 1 to the range(int ((d1 - d).days))
.
def daterange(d, d1):
for n in range(int ((d1 - d).days) + 1):
yield d + timedelta(n)
The reason for this is that, as per documentation, range(stop)
does not output the stop value, but only the values 'before' it.
Upvotes: 4