Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to prepare a Python date object to be inserted into MongoDB?
MongoDB stores dates in ISODate format. PyMongo (the official MongoDB driver for Python) directly supports Python's datetime.datetime objects, which are automatically converted to ISODate when inserted. There are three common ways to prepare date objects for MongoDB.
Method 1: Current UTC Timestamp
Use datetime.datetime.utcnow() to insert the current UTC time ?
import datetime
from pymongo import MongoClient
client = MongoClient()
db = client.test_database
result = db.objects.insert_one({"last_modified": datetime.datetime.utcnow()})
print("Date Object inserted")
Date Object inserted
Method 2: Specific Date
Use datetime.datetime(year, month, day, hour, minute) for a fixed date ?
import datetime
from pymongo import MongoClient
client = MongoClient()
db = client.test_database
specific_date = datetime.datetime(2022, 12, 25, 15, 30)
db.events.insert_one({"event_date": specific_date})
print("Specific date inserted!")
Specific date inserted!
Required parameters: year, month, day. Optional: hour, minute, second, microsecond, tzinfo.
Method 3: Relative Dates with timedelta
Use datetime.timedelta to calculate past or future dates ?
import datetime
from pymongo import MongoClient
client = MongoClient()
db = client.test_database
# 7 days ago
seven_days_ago = datetime.datetime.utcnow() - datetime.timedelta(days=7)
db.logs.insert_one({"log_date": seven_days_ago})
print("Log date inserted!")
# 30 days in the future
future_date = datetime.datetime.utcnow() + datetime.timedelta(days=30)
db.reminders.insert_one({"remind_date": future_date})
print("Future date inserted!")
Log date inserted! Future date inserted!
Summary
| Method | Use Case |
|---|---|
datetime.datetime.utcnow() |
Current UTC timestamp |
datetime.datetime(y, m, d) |
Specific fixed date/time |
datetime.timedelta(days=n) |
Relative past/future dates |
Conclusion
PyMongo automatically converts Python datetime.datetime objects to MongoDB's ISODate format. Use utcnow() for current timestamps, the datetime() constructor for specific dates, and timedelta for relative date calculations.
