MongoDB/PyMongo/Python(Time):获取字符串形式的Datetime



我的文档中有一个MongoDB数据库,其结构如下:

> "_id": {
>       "mandant": "a4da7117-2763-48df-b3a3-d50a0f6006fe",
>       "ersteller": "9bc79ce4-c23a-4c24-a857-80f94a341d39",
>       "sender": "9bc79ce4-c23a-4c24-a857-80f94a341d39",
>       "vorgang": "c08382ed-143f-46f7-8382-ed143f26f7b8",
>       "nachricht": "6c9d3386-001f-4809-9d33-86001fd80990"
>     },
>     "_class": "de.codecraft.amt.storage.model.XAmtshilfe",
>     "created": {
>       "$date": "2018-10-02T09:20:05.060Z"
>     },

当我用查询时

collection = db.find({}, {"_id": 0, "created": 1})

我得到了以下结果:

{'created': datetime.datetime(2018, 11, 30, 13, 40, 4, 879000)}

如何达到纯datetime值,以便能够将其解析为其他形式的时间类型

谢谢

PyMongo将时间戳投射到本机datetime.datetime结构中。然后可以使用.isoformat().strftime(<format>)方法将其转换为字符串。

所以,继续你的例子

objects = db.find({}, {"_id": 0, "created": 1})
for obj in objects:
dt = obj['created']
time_str = dt.isoformat()
# ...

如果有人不仅想转换文档中的单个datetime值,还想转换文档的所有值,下面的json编码器可能会有所帮助。

import json
import datetime
class MongoDbEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.astimezone().strftime("%Y-%m-%dT%H:%M:%S.%f%z")
return json.JSONEncoder.default(self, obj)
# usage
json_document = json.dumps(result, cls=MongoDbEncoder)

我从UUID转换中得到了一个提示。

您也可以在查询过程中转换为字符串:

pipe =
[  
{  
"$project":{  
"_id":0,
"created":{ "$dateToString":{"format":"%Y%m%dT%H%M", "date":"$created"}},
}
}
]
objects = db.aggregate(pipeline=pipe)

最新更新