Reputation: 2331
I am trying to filter mongo data with dates.
For that I am using these sets of data:
def mongo_db(mydict):
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient[<Db name>]
mycol = mydb[<Collection name>]
# mydict = {}
x = mycol.insert_one(mydict)
# print(x.inserted_id)
return x.inserted_id
for i in range(1,6):
mydict = {
"startsAt": {
"time": {
"date": datetime.datetime.today() - timedelta(days = i) + timedelta(hours = i)
},
"valid": True
}
}
I am trying to filter certain date fro example above code generate data like:
"2021-02-09T13:56:09.963000Z"
"2021-02-09T13:56:09.963001Z"
And I want my result to be like if 2021-02-09 then filter only that.
When I am using this code:
filterCondition = {
"startsAt.time.date" : { "$lt" : datetime.datetime.today()},
"startsAt.time.date" : { "$gt" : datetime.datetime.today() - timedelta(days=1)}
}
mycol.find(filterCondition)
I am getting current day:
"2021-02-10T00:31:47.411000Z"
I need to filter date yesterday and a day after yesterday only.
I have tried this format:
from_dt = datetime.datetime.strptime('2021-02-10','%Y-%m-%d')
#from_dts = datetime.utcfromtimestamp(from_dt)
to_dt = datetime.datetime.strptime('2021-02-08','%Y-%m-%d')
But no luck so I need 24 hrs full day result of yesterday. I am confused about datetime what will be yesterday? Meaning If I have record:
"2021-02-09T13:56:09.963000Z"
"2021-02-09T13:56:09.963001Z"
"2021-02-09T13:56:09.963002Z"
.....
Then I only want this date 2021-02-09
Upvotes: 0
Views: 768
Reputation: 8814
If you are using native BSON dates, all dates are stored as UTC; so if you want to seach from UTC 00:00 yesterday to UTC 00:00 today use:
today = datetime.date.today()
yesterday = datetime.date.today() - datetime.timedelta(days=1)
start = datetime.datetime.combine(yesterday, datetime.time(0, 0)).replace(tzinfo=pytz.utc)
end = datetime.datetime.combine(today, datetime.time(0, 0)).replace(tzinfo=pytz.utc)
print(list(db.mycollection.find({'date': {'$gte': start, '$lt': end}})))
Upvotes: 1