Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert datetime string into Mongodb as ISODate using pymongo

Tags:

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")

like image 335
ArchieTiger Avatar asked Feb 02 '17 09:02

ArchieTiger


People also ask

How do I use ISODate in Python?

To get an ISO 8601 date in string format in Python 3, you can simply use the isoformat function. It returns the date in the ISO 8601 format. For example, if you give it the date 31/12/2017, it'll give you the string '2017-12-31T00:00:00'.

How is datetime stored in MongoDB?

MongoDB will store date and time information using UTC internally, but can easily convert to other timezones at time of retrieval as needed.

What is ISODate in MongoDB?

You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.


1 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

like image 64
jas Avatar answered Sep 29 '22 15:09

jas