Datetime, MongoDB. 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 example. Please 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().
Info We specify the dates by subtracting 200 or 100 days from the result value of datetime.today.
Then We find posts that have dates within the last 150 days. We then find posts that are older than 180 days.
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')}
Notes, find. 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.
A review. With datetime and timedelta, we can handle relative dates and times in Python. MongoDB can convert and handle dates created in this way.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 11, 2023 (edit).