【发布时间】:2021-03-29 16:09:25
【问题描述】:
我有以下类型的 json 文档,我需要使用 pymongo 将其插入到 mongodb 集合中:
json={
"resource": "/items/6791111",
"user_id": 123456789,
"topic": "items",
"application_id":001,
"attempts": 1,
"sent": "2020-07-22T15:53:06.000-04:00",
"received":"2020-07-22T15:53:06.000-04:00"
}
发送和接收的字段是字符串,所以如果我运行:
collection.insert_one(json)
这将在数据库中保存为字符串,如何直接存储为日期?
我尝试过这样的事情:
from dateutil.parser import parse
json['sent']=parse(json['sent'])
collection.insert_one(json)
但在我看来这不是一个很好的解决方案,因为我的文档在某些情况下有多个日期字段,或者有时某些日期字段为空(例如,在订单中交付的字段可能为空,直到订单交付)
something like this:
json2={
"resource": "/items/6791111",
"user_id": 123456789,
"topic": "items",
"application_id":001,
"attempts": 1,
"sent": "2020-07-22T15:53:06.000-04:00",
"received":Null
}
现在我正在使用函数手动解析日期,但它真的一点用都没有
我需要将日期字段解析为日期,以便按时间过滤。
【问题讨论】:
-
if语句还不错。