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")
Asked
Active
Viewed 5.4k times
28

ArchieTiger
- 2,083
- 8
- 30
- 45
-
Take a look: https://docs.mongodb.com/manual/core/shell-types/ and https://docs.mongodb.com/manual/reference/method/Date/ – Denis V Feb 02 '17 at 10:00
-
You can go [there](https://stackoverflow.com/a/7651332/18036318) to find a solution that worked for me – Robin Jan 26 '22 at 14:46
-
A solution that worked for me : [on this other thread](https://stackoverflow.com/a/7651332/18036318) – Robin Jan 26 '22 at 14:51
2 Answers
34
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

jas
- 10,715
- 2
- 30
- 41
-
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" – Mirko May 17 '17 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'" – Sohail Apr 21 '18 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 the `T` separating the date from the time, nor the trailing `Z`. Hence these need to be removed from the format string. – jas Apr 21 '18 at 21:56
-
python **datetime** object has **isoformat** method, e.g. `datetime.datetime.now().toisoformat()` is enough for current datetime as iso format – Guru Vishnu Vardhan Reddy Sep 14 '20 at 04:01
-
I tested `datetime.datetime.now().toisoformat()` and found `datetime.datetime.now().isoformat()` works in python 3.8. Maybe syntax changed? – Marc Maxmeister Sep 07 '21 at 21:24
2
use dateutil
dateutil.parser.parse("2017-10-13T10:53:53.000Z")
will return datetime.datetime(2017, 10, 13, 10, 53, 53, tzinfo=tzutc())

DevEx
- 4,337
- 13
- 46
- 68