crl_qjx
crl_qjx

Reputation: 93

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

Upvotes: 3

Views: 6840

Answers (2)

Belly Buster
Belly Buster

Reputation: 8844

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

Upvotes: 2

Tom Slabbaert
Tom Slabbaert

Reputation: 22316

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)

Upvotes: 1

Related Questions