Python 如何使用pymongo将日期时间字符串作为ISODate插入Mongodb
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41999094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to insert datetime string into Mongodb as ISODate using pymongo
提问by ArchieTiger
How to insert datetime string like this "2017-10-13T10:53:53.000Z"
into mongo db as ISODate?
I get a string in mongodb when I insert:
datetime.strptime("2017-10-13T10:53:53.000Z", "%Y-%m-%dT%H:%M:%S.000Z")
如何将这样的日期时间字符串"2017-10-13T10:53:53.000Z"
作为 ISODate插入到 mongo db 中?当我插入时,我在 mongodb 中得到一个字符串:
datetime.strptime("2017-10-13T10:53:53.000Z", "%Y-%m-%dT%H:%M:%S.000Z")
回答by jas
This works for me, do you get a different result?
这对我有用,你得到不同的结果吗?
from pymongo.mongo_client import MongoClient
import datetime
d = datetime.datetime.strptime("2017-10-13T10:53:53.000Z", "%Y-%m-%dT%H:%M:%S.000Z")
with MongoClient() as mongo:
db = mongo.get_database("test")
db['dates'].insert({"date" : d})
Check in mongo:
签入mongo:
> use test
switched to db test
> db.dates.findOne()
{
"_id" : ObjectId("589307d7cfd6c908d4b677d6"),
"date" : ISODate("2017-10-13T10:53:53Z")
}
UPDATE: As commented, if you get a "time data does not match format" error, try a more general format string such as: %Y-%m-%dT%H:%M:%S.%fZ
更新:如评论中所述,如果您收到“时间数据与格式不匹配”错误,请尝试使用更通用的格式字符串,例如:%Y-%m-%dT%H:%M:%S.%fZ
回答by DevEx
use dateutil
dateutil.parser.parse("2017-10-13T10:53:53.000Z")
will return datetime.datetime(2017, 10, 13, 10, 53, 53, tzinfo=tzutc())
使用dateutil
dateutil.parser.parse("2017-10-13T10:53:53.000Z")
将返回datetime.datetime(2017, 10, 13, 10, 53, 53, tzinfo=tzutc())