Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

1K
Views
Pymongo : How to insert a document with a timestamp

I would like to insert in a database a document with a timestamp and not a date. If I insert the following document:

data = {'dt': dt.datetime.today().timestamp()}

The timestamp will be inserted as a double: Double example

What I would like is to have this type of data:

mongo timestamp example

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Just to throw something extra in, the default _id field that is created automatically contains a "timestamp", and you can retrieve it using the generation_time property of the ObjectId object, without having to add your own field in e.g.:

from pymongo import MongoClient

db = MongoClient()['mydatabase']

db.mycollection.insert_one({'a': 1})
record = db.mycollection.find_one({'a': 1})
print(record.get('_id').generation_time)

prints:

2021-03-14 17:08:51+00:00
over 4 years ago · Santiago Trujillo Report

0

While Mongo does have a timestamp the docs do say the following:

The BSON timestamp type is for internal MongoDB use. For most cases, in application development, you will want to use the BSON date type. See Date for more information.

Note that using timestamp type can also have issues with different driver support and issues regarding operator behaviour. pymongo uses datetime.datetime objects for representing dates and times in MongoDB documents. And as you are already using datetime I would suggest just saving that as a Date not a timestamp.

If for whatever reason you insist on using timestamp type then you would need to use bson.timestamp type like so:`

from bson.timestamp import Timestamp
import datetime as dt
timestamp = Timestamp(int(dt.datetime.today().timestamp()), 1)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!