简体   繁体   English

Pymongo:如何插入带有时间戳的文档

[英]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:时间戳将作为双精度插入: 双重例子

What I would like is to have this type of data:我想要的是拥有这种类型的数据:

mongo 时间戳示例

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 eg:只是添加一些额外的东西,自动创建的默认_id字段包含一个“时间戳”,您可以使用 ObjectId object 的generation_time属性检索它,而无需在例如添加您自己的字段:

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

While Mongo does have a timestamp the docs do say the following:虽然 Mongo 确实有时间戳,但文档确实说了以下内容:

The BSON timestamp type is for internal MongoDB use. BSON 时间戳类型供内部 MongoDB 使用。 For most cases, in application development, you will want to use the BSON date type.大多数情况下,在应用程序开发中,您会希望使用 BSON 日期类型。 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. pymongo 使用datetime.datetime对象来表示 MongoDB 文档中的日期和时间。 And as you are already using datetime I would suggest just saving that as a Date not a timestamp.而且由于您已经在使用datetime我建议将其保存为Date而不是时间戳。

If for whatever reason you insist on using timestamp type then you would need to use bson.timestamp type like so:`如果出于某种原因您坚持使用timestamp类型,那么您将需要使用bson.timestamp类型,如下所示:`

from bson.timestamp import Timestamp
import datetime as dt
timestamp = Timestamp(int(dt.datetime.today().timestamp()), 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM