Home
MongoDB
datetime Use
Updated Oct 11, 2023
Dot Net Perls
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Oct 11, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen