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
当我查看 RockMongo 中的条目时,它只是显示:
"entry_time": "Mon Jan 18 2016 23:59:51 GMT+1000 (AEST)"
但是根据这个答案:
https://stackoverflow.com/a/3778820/1063287
它应该看起来像这样:
ISODate("2014-02-10T10:50:57.240Z")
如何通过 Python 将 Javascript new Date() 作为 ISODate
插入 MongoDB?
编辑:
我也刚刚尝试过这个:
Javascript
var theTime = new Date();
var theTime = theTime.toISOString()
$.getJSON("/my_path",{
the_time: theTime,
format: 'json'
});
RockMongo 中的结果如下:
"entry_time": "2016-01-18T14:35:09.226Z"
最佳答案
JavaScript
var date = new Date();
var isoDateString = date.toISOString();
$.getJSON("/save_date",{isoDateString: isoDateString, format: 'json'}, function(results) {
});
在Python中解析UTC日期字符串并将日期对象保存到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);
结果
"date_object" : ISODate("2016-08-21T06:41:19.319Z"),
希望这对您有帮助。
关于javascript - 如何通过Python将Javascript new Date()插入MongoDB?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34857093/