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")
-
Take a look: docs.mongodb.com/manual/core/shell-types and docs.mongodb.com/manual/reference/method/Date– Denis VFeb 2, 2017 at 10:00
-
You can go there to find a solution that worked for me– RobinJan 26, 2022 at 14:46
-
A solution that worked for me : on this other thread– RobinJan 26, 2022 at 14:51
2 Answers
This works for me:
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:
> 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
-
2I got a "time data does not match format", and had to change slightly the format string to: "%Y-%m-%dT%H:%M:%S.%fZ"– MirkoMay 17, 2017 at 11:10
-
1It didn't work even changing to @Mirko format , "ValueError: time data '1970-01-18 20:15:07.234807' does not match format '%Y-%m-%dT%H:%M:%S.%fZ'"– SohailApr 21, 2018 at 20:19
-
@Sohail, for that value the format would be
"%Y-%m-%d %H:%M:%S.%f"
(Note that your value does not include theT
separating the date from the time, nor the trailingZ
. Hence these need to be removed from the format string.– jasApr 21, 2018 at 21:56 -
python datetime object has isoformat method, e.g.
datetime.datetime.now().toisoformat()
is enough for current datetime as iso format Sep 14, 2020 at 4:01 -
I tested
datetime.datetime.now().toisoformat()
and founddatetime.datetime.now().isoformat()
works in python 3.8. Maybe syntax changed? Sep 7, 2021 at 21:24
use dateutil
dateutil.parser.parse("2017-10-13T10:53:53.000Z")
will return datetime.datetime(2017, 10, 13, 10, 53, 53, tzinfo=tzutc())