gpt4 book ai didi

python - 使用 pymongo 将当前时间插入 mongo

转载 作者:IT老高 更新时间:2023-10-28 13:34:07 26 4
gpt4 key购买 nike

当创建新文档时,我正在尝试以特定格式存储当前时间。以下是调用无效方法的部分代码:

    dbm = AccountsDB()
dbm.store_info(user_info)

这里是实际的 AccountsDB() 类:

#! /usr/bin/env python2.7

import pymongo
import datetime
import time

class AccountsDB():
def store_info(self, user_info=None):
try:
conn = pymongo.Connection('localhost', 27017)
db_name = 'accountsdb'
coll_name = 'user_info'

db = conn[db_name]
coll = db[coll_name]
print "Successfully connected to '%s'" % db_name

now = datetime.datetime.now()
if user_info is not None:
now = datetime.datetime.now()
'''
This is not Working...

created_time = {
'created_time': {
'day': now.day,
'month': now.month,
'year': now.year,
'hour': now.hour,
'minute': now.minute,
'second': now.second,
'microsecond': now.microsecond
}
}
user_info.append(created_time)
'''
print user_info
coll.insert(user_info)
else:
print 'No user_info'
print "Data where stored in database"
except:
print "Some Error Occured"

我希望文档看起来像这样:

> db.user_info.find().pretty()
{
"_id" : ObjectId("50d8ded1bdbff3401c252f1a"),
"ip" : "24.xx.xx.xx",
"region_code" : "MA",
"region_name" : "Massachusetts",
"secret_answer2" : "Mercedes",
"l_name" : "Flores",
"f_name" : "Jacob",
"country_name" : "United States",
// I want to add next objects to the document
'created_time': {
'day': 10,
'month': 11,
'year': 12,
'hour': 11,
'minute': 11,
'second': 22,
'microsecond': 1234
}
}

最佳答案

看起来您希望 python 代码在 pymongo 调用中将当前时间传递给 mongo。你这个:

>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2012, 12, 24, 18, 33, 46, 266943)

完整的代码如下所示:

import pymongo
from datetime import datetime

class AccountsDB():
def __init__(self):
pass
def store_info(self, user_info=None):
try:
conn = pymongo.Connection('localhost', 27017)
db_name = 'accountsdb'
coll_name = 'user_info'
db = conn[db_name]
coll = db[coll_name]
print "Successfully connected to '%s'" % db_name
if user_info is not None:
user_info['created_time'] = datetime.now()
print user_info
coll.insert(user_info)
else:
print 'No user_info'
print "Data where stored in database"
except:
print "Some Error Occured"

a = AccountsDB()
a.store_info({})

关于python - 使用 pymongo 将当前时间插入 mongo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14026392/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com