Dates are essential in a database. A document may have a created, modified, or even deleted date—these timestamps can be queried with find()
.
In MongoDB we use the datetime
Python module directly to encode and handle dates. We use "$lt" and "$gt" for range queries of dates.
Date
time examplePlease notice how we import parts of the datetime
module with "import" statements at the top. We use relative dates here—based on the value of datetime.today()
.
datetime.today
.from pymongo import MongoClient from datetime import datetime from datetime import timedelta client = MongoClient("mongodb://127.0.0.1:27017") db = client.blog # Reset. db.posts.delete_many({}) # Get today. today = datetime.today() # Insert some blog posts. db.posts.insert_many([ {"title": "Intro Post", "date": today - timedelta(days=200)}, {"title": "Taking a Break", "date": today - timedelta(days=100)}, {"title": "Goodbye Blog", "date": today}, ]) # Find posts within last 150 days. print("FIND :: RECENT POSTS") cursor = db.posts.find({"date": {"$gt": today - timedelta(150)}}) for doc in cursor: print(doc) # Find posts more than 180 days ago. print("FIND :: OLDER POSTS") cursor = db.posts.find({"date": {"$lt": today - timedelta(180)}}) for doc in cursor: print(doc)FIND :: RECENT POSTS {'date': datetime.datetime(2017, 7, 20, 12, 54, 13, 183000), 'title': 'Taking a Break', '_id': ObjectId('59f4e065251497165850cd1f')} {'date': datetime.datetime(2017, 10, 28, 12, 54, 13, 183000), 'title': 'Goodbye Blog', '_id': ObjectId('59f4e065251497165850cd20')} FIND :: OLDER POSTS {'date': datetime.datetime(2017, 4, 11, 12, 54, 13, 183000), 'title': 'Intro Post', '_id': ObjectId('59f4e065251497165850cd1e')}
Usually we want to find documents within a range of dates—either greater than, less than, or with both constraints. We can combine these queries into a single find call.
With datetime
and timedelta
, we can handle relative dates and times in Python. MongoDB can convert and handle dates created in this way.