我重新问这个问题,因为似乎有一些误解。我需要使用 Python 将 mongo 中的字符串转换为日期格式。我有以下代码:
newest_date = datetime.strptime(r["date"], "%Y-%m-%d").isoformat()
其中成功创建了以下日期对象(new_date):
2017-01-03T00:00:00
当我尝试:
db.address.update_one({"address": "1234", {"$set": {"date" : new_date}})
我在文档中更新了项目,但它仍然是一个字符串,而不是日期。我可以使用以下命令在 shell 中成功执行此操作:
db.address.find({ "date" : { $type : 2 } } ).forEach(function(element){ element.date = ISODate(element.date); db.address.save(element);})
如何将实际类型更新为日期,因为当我从控制台执行此操作时,我得到输出:
"date": {"$date": "2017-06-28T00:00:00.000Z"
},
希望这会帮助别人不要犯我犯的愚蠢错误。确保不要像小丑一样将 .isoformat() 附加到日期时间对象...
newest_date = datetime.strptime(r["date"], "%Y-%m-%d")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句