javascript - 如何通过Python将Javascript new Date()插入MongoDB?

标签 javascript python mongodb

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/

相关文章:

python - 使用Pycharm调试django meet错误

python - 计算嵌套列表中每个位置的出现次数

python - 将列表转换为元组的分组列表?

javascript - Mongodb:如何在不知道字段名称的情况下读取值?

node.js - Mongoose 私聊消息模型

javascript - 支持动态过滤的GWT Table

javascript - 防止 Angular 模板初始显示

javascript - 文件错误{代码: 5} trying to use absolute file paths with Meteor 1. 4 Cordova

javascript - mouseup 事件停止 firefox 上的 click 事件

ruby-on-rails - Mongoid 使用 has_one 将一个对象与同一类的两个不同对象相关联