使用pymongo将当前日期插入mongodb

时间:2012-12-24 23:11:01

标签: python mongodb pymongo

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

    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
    }
}

2 个答案:

答案 0 :(得分:8)

看起来你想让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({})

答案 1 :(得分:1)

pymongo建议您只使用datetime.datetime.utcnow()

  

例如,以下代码存储当前UTC日期和时间   进入MongoDB:

     

>>> result = db.objects.insert_one( ... {"last_modified": datetime.datetime.utcnow()})

     

始终使用datetime.datetime.utcnow(),它以UTC返回当前时间,而不是datetime.datetime.now(),它返回当前本地时间。避免   这样做:

     

>>> result = db.objects.insert_one( ... {"last_modified": datetime.datetime.now()})

pymongo datetimes