1

Javascript

theTime = new Date();
$.getJSON("/my_path",{
    the_time: theTime,
    format: 'json'
});

Python

var the_time = request.GET.the_time
# the entry
entry = {}
# other key/values are added to entry
entry['entry_time'] = entry_time
# the document
new_document = {}
# the entry is nested in the new document
new_document['k1']['n1'].append(entry)
collection.insert(new_document)

MongoDB

When I look at the entry in RockMongo, it is just showing:

"entry_time": "Mon Jan 18 2016 23:59:51 GMT+1000 (AEST)"

But according to this answer:

https://stackoverflow.com/a/3778820/1063287

It should look something like this:

ISODate("2014-02-10T10:50:57.240Z")

How do I insert the Javascript new Date() to MongoDB as an ISODate via Python?

Edit:

I also just tried this:

Javascript

var theTime = new Date();
var theTime = theTime.toISOString()
$.getJSON("/my_path",{
    the_time: theTime,
    format: 'json'
});

And it results in this in RockMongo:

"entry_time": "2016-01-18T14:35:09.226Z" 
Community
  • 1
  • 1
user1063287
  • 10,265
  • 25
  • 122
  • 218
  • Instead of passing a string to Mongo you should pass it a Python [`datetime` object](http://api.mongodb.org/python/current/examples/datetimes.html). [`dateutil.parser.parse`](http://dateutil.readthedocs.org/en/latest/parser.html#dateutil.parser.parse) should be able to parse the string: `"Mon Jan 18 2016 23:59:51 GMT+1000 (AEST)"` – Ashwini Chaudhary Jan 18 '16 at 14:36
  • `from dateutil.parser import *` then `parse("Mon Jan 18 2016 23:59:51 GMT+1000 (AEST)")` returns `datetime.datetime(2016, 1, 18, 23, 59, 51, tzinfo=tzlocal())`. – user1063287 Jan 18 '16 at 14:44
  • and what is wrong with you getting `datetime` object? – styvane Jan 18 '16 at 14:46

1 Answers1

1

JavaScript

var date = new Date();
var isoDateString =  date.toISOString();
$.getJSON("/save_date",{isoDateString: isoDateString, format: 'json'}, function(results) {
});

Parse UTC date string in Python and save date object into MongoDB.

Python

import datetime
isoDateString = request.GET.isoDateString
date_object = datetime.datetime.strptime(isoDateString, '%Y-%m-%dT%H:%M:%S.%fZ')
document = {}
document['date_object'] = date_object
# define database
dbname = 'my_database'
# define collection
collection = db.my_collection
# insert document
collection.insert(document);

Result

"date_object" : ISODate("2016-08-21T06:41:19.319Z"),

Hope this help you.

user1063287
  • 10,265
  • 25
  • 122
  • 218
basit raza
  • 661
  • 2
  • 6
  • 18