我正在使用postgresql
。在它上面我有我必须在python上使用的数据。
一个表字段包含日期。它看起来像这样:
在我的python脚本上使用psycopg2
我正在制作结果,当我得到日期时,它会在mongodb上保存为字符串
"created" : "2016-06-16T19:53:43.776456"
我的代码如下所示:
query = "SELECT name, created FROM user;"
cur.execute(query)
user_data = cur.fetchall()
for user_info in user_data:
user_json = {
'name': user_info[0],
'created': user_info[1]
}
我想将此"created" : "2016-06-16T19:53:43.776456"
转换为"created" : ISODate("2016-06-24T09:08:09.333Z")
,但我不知道如何以正确的格式转换它。请帮忙!
答案 0 :(得分:1)
IMO在将数据存储到MongoDB时无需指定ISODate
。
Python代码(片段):
cur.execute("select name, created from tt_user;")
data = cur.fetchall()
for row in data:
print(row[0], row[1])
mdr = {
'user': row[0],
'created': row[1]
}
mongo_db.tt_user.insert_one(mdr)
print("Done.")
print("Check data in MongoDB");
for row in mongo_db.tt_user.find():
print(row)
及其输出:
Load data from PostgreSQL into MongoDB...
('user1', datetime.datetime(2016, 6, 29, 13, 26, 28, 632436, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=180, name=None)))
('user2', datetime.datetime(2016, 6, 29, 13, 26, 28, 632739, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=180, name=None)))
('user3', datetime.datetime(2016, 6, 29, 13, 26, 28, 632751, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=180, name=None)))
('user4', datetime.datetime(2016, 6, 29, 13, 26, 28, 632757, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=180, name=None)))
('user5', datetime.datetime(2016, 6, 29, 13, 26, 28, 632762, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=180, name=None)))
Done.
Check data in MongoDB....
{u'_id': ObjectId('5773a254afd34b43d76aa792'), u'user': u'user1', u'created': datetime.datetime(2016, 6, 29, 10, 26, 28, 632000)}
{u'_id': ObjectId('5773a255afd34b43d76aa793'), u'user': u'user2', u'created': datetime.datetime(2016, 6, 29, 10, 26, 28, 632000)}
{u'_id': ObjectId('5773a255afd34b43d76aa794'), u'user': u'user3', u'created': datetime.datetime(2016, 6, 29, 10, 26, 28, 632000)}
{u'_id': ObjectId('5773a255afd34b43d76aa795'), u'user': u'user4', u'created': datetime.datetime(2016, 6, 29, 10, 26, 28, 632000)}
{u'_id': ObjectId('5773a255afd34b43d76aa796'), u'user': u'user5', u'created': datetime.datetime(2016, 6, 29, 10, 26, 28, 632000)}
在MongoDB控制台中:
> db.tt_user.find()
{ "_id" : ObjectId("5773a254afd34b43d76aa792"), "user" : "user1", "created" : ISODate("2016-06-29T10:26:28.632Z") }
{ "_id" : ObjectId("5773a255afd34b43d76aa793"), "user" : "user2", "created" : ISODate("2016-06-29T10:26:28.632Z") }
{ "_id" : ObjectId("5773a255afd34b43d76aa794"), "user" : "user3", "created" : ISODate("2016-06-29T10:26:28.632Z") }
{ "_id" : ObjectId("5773a255afd34b43d76aa795"), "user" : "user4", "created" : ISODate("2016-06-29T10:26:28.632Z") }
{ "_id" : ObjectId("5773a255afd34b43d76aa796"), "user" : "user5", "created" : ISODate("2016-06-29T10:26:28.632Z") }
>
所以这是客户端软件的行为,而不是存储问题。只需将数据保存为日期时间。
PS:谢谢你强迫我最后安装MongoDB:)
答案 1 :(得分:0)
替换此
query = "SELECT name, created FROM user;"
由此
query = "SELECT name, 'ISODate(\"' || created || '\")' FROM user;"
查询将返回您要存储为created
的格式良好的字符串。