Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

1K
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda