Create an ISODate with pyMongo
Asked Answered
P

5

45

I've been trying to find a way to create an ISODate object whith pyMongo client, but without any success so far.

I use http://pypi.python.org/pypi/pymongo3 client, which is the only serious one available in Python 3 for now, but the problem doesn't seem to come from this specific pymongo version.

I'd like to know if any of you has found a solution to use this MongoDB object type from a pymongo client... thanks for your help !

Prosperity answered 4/10, 2011 at 16:26 Comment(1)
if you need to convert a date other than "now" , you may also want to add timezone info to your datetime , before getting the utc valueBrundisium
M
79

You just need to store an instance of datetime.datetime.

Inserting from the python shell:

>>> c.test.test.insert({'date': datetime.datetime.utcnow()})
ObjectId('4e8b388367d5bd2de0000000')
>>> c.test.test.find_one()
{u'date': datetime.datetime(2011, 10, 4, 16, 46, 59, 786000), u'_id': ObjectId('4e8b388367d5bd2de0000000')}

Querying in the mongo shell:

> db.test.findOne()
{
    "_id" : ObjectId("4e8b388367d5bd2de0000000"),
    "date" : ISODate("2011-10-04T16:46:59.786Z")
}
Marcellus answered 4/10, 2011 at 16:51 Comment(5)
Does not seem to work, the stored data is a string. "timestamp" : "Wed Oct 05 2011 09:56:02 GMT+0200 (CET)",Prosperity
What version of MongoDB are you using?Marcellus
Also, ISODate isn't a BSON type. That's just the way a BSON Datetime is represented in the shell. In PyMongo it's represented as an instance of datetime.datetime. bsonspec.org/#/specificationMarcellus
My MongoDB was < 1.7, once upgraded it works fine when I push datetime.datetime instances.Prosperity
so easy. searched for this everywhere. Thanks a lot.Schoolfellow
G
17

For those who are wondering how to create ISODate from timestamp:

ts = time.time()
isodate = datetime.datetime.fromtimestamp(ts, None)

This will create datetime object with no timezone. When inserted to MongoDB it will get converted to proper ISODate().

Also, I strongly recommend looking at Python TimeTransitionsImage. Note that tuple here is named tuple (equivalent to struct in C). And also note that tuple fields are not the same as in C counterparts, even though the naming is the same (for instance, tm_wday starts with Monday and not Sunday).

Goral answered 6/3, 2012 at 14:17 Comment(1)
fromtimestamp() create a naive datetime object that represents time in the local timezone of your server: it is not what you want in most cases. You should use datetime.utcfromtimestamp(ts) instead.Latashalatashia
R
4

Actually that does not work either. When you try to use either utcfromtimestamp or fromtimestamp, the program errors out saying that it needs a float. Just parse the string into a date time object and use that directly in the Mongodb. filter

from_dt = datetime.strptime('2018-04-01','%Y-%m-%d')
#from_dts = datetime.utcfromtimestamp(from_dt)
to_dt = datetime.strptime('2018-04-30','%Y-%m-%d')
#to_dts = datetime.utcfromtimestamp(to_dt)
filterCondition = { 
    "LastLogin" : { "$lte" : to_dt},
    "LastLogin" : { "$gte" : from_dt}
}

And then

db[(colName)].find({ "<colName>" : filterCondition }) 

Would work...

Registrar answered 26/6, 2018 at 21:51 Comment(0)
G
1
result = db.objects.insert_one(
   {"last_modified": datetime.datetime.utcnow()})

Here utc stands for Universal Time Coordinates.

Grubstake answered 26/7, 2016 at 14:58 Comment(1)
Welcome to Stack Overflow. You could make this a better answer by adding some explanation of what the code is doingDelacroix
B
0

For create a document with specific date, for example 03/10/1999, run this:

from datetime import datetime
from pymongo import MongoClient

db = MongoClient().db_name

date = datetime(1999, 03, 10)
db.collection.insert_one({'date': date})
Bartholomeo answered 20/8, 2021 at 6:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.