Prepare Python Date Object for MongoDB Insertion



We can use the PyMongo library (the official Mongodb driver for Python) to connect to a Mongodb database and use it to insert, update, delete, etc objects. To include date and time information, Mongodb supports ISODate format, and PyMongo provides direct support for Python's datetime.datetime objects.

There are multiple ways to prepare a Python date object for insertion into MongoDB, which we will discuss here:

Create and Insert Date Object to MongoDB Using datetime.datetime.utcnow()

The simplest way to create a Python date object that can be inserted into MongoDB is by using datetime.datetime.utcnow() from the datetime module. You can use this function to provide the current UTC timestamp when calling db.objects.insert_one() in MongoDB.

Example

The following program connects to a Mongodb database, inserts a new document with a "last_modified" field set to the current UTC timestamp, then prints a confirmation message:

import datetime
from pymongo import MongoClient

# Connect to MongoDB on default host and port
client = MongoClient()
db = client.test_database

# Insert a document with the current UTC date
result = db.objects.insert_one({"last_modified": datetime.datetime.utcnow()})
print("Date Object inserted")

Following is the output of the above code:

Date Object inserted

Create and Insert Specific Date Using datetime.datetime()

A date object can also be created using the datetime.datetime() constructor, which can be used for inserting dates into a MongoDB database. To create a date object with this constructor, you need to specify these parameters: year, month, day, hour, minute, second, microsecond, and tzinfo (time zone). Where, year, month, and day are required, others are optional.

Example

The following program creates a datetime object representing December 25, 2022 at 3:30 PM, and inserts it as the value for the key "event_date" within a document in the 'events' collection:

import datetime
from pymongo import MongoClient

client = MongoClient()
db = client.test_database

# Create a specific date
specific_date = datetime.datetime(2022, 12, 25, 15, 30)

# Insert it into MongoDB
db.events.insert_one({"event_date": specific_date})
print("Specific date inserted!")

Following is the output of the above code:

Specific date inserted!

Create and Insert Relative Dates Usingdatetime.timedelta

Whenever you need to store timestamps for future or past events, you need to create a relative date for it. To create relative date such as difference between two dates or times, you can use datetime.timedelta, which is a class within the datetime module. It allows us to add or subtract specific amounts of time (like days, hours, minutes, etc.) from a date or datetime object. By using this method.

By using this, we can create an object of relative dates that can be passed to the MongoDB function to insert the date.

Example

The following Python script connects us to MongoDB database and calculates a date seven days in the past using datetime.timedelta, then inserts this date as a "log_date" field into a "logs" collection:

import datetime
from pymongo import MongoClient

client = MongoClient()
db = client.test_database

# Calculate a date 7 days ago
seven_days_ago = datetime.datetime.utcnow() - datetime.timedelta(days=7)

# Insert the date
db.logs.insert_one({"log_date": seven_days_ago})
print("Log date inserted!")

Following is the output of the above code:

Log date inserted!
Updated on: 2025-06-03T15:12:08+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements