I'm trying to store a current time in specific format, when new document where created. Here is the part of the code that call's not working method:
dbm = AccountsDB()
dbm.store_info(user_info)
And here is the actual AccountsDB() class:
#! /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"
I want document looks something like this:
> 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
}
}
It looks like you want python code to pass the current time to mongo in a pymongo call. You this:
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2012, 12, 24, 18, 33, 46, 266943)
Complete code looks like this:
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({})
pymongo suggests you should simply use datetime.datetime.utcnow()
For example, the following code stores the current UTC date and time into MongoDB:
>>> result = db.objects.insert_one( ... {"last_modified": datetime.datetime.utcnow()})
Always use datetime.datetime.utcnow(), which returns the current time in UTC, instead of
datetime.datetime.now()
, which returns the current local time. Avoid doing this:
>>> result = db.objects.insert_one( ... {"last_modified": datetime.datetime.now()})
pymongo datetimes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With