Create an ISODate with pyMongo

前端 未结 4 1713
春和景丽
春和景丽 2020-12-01 06:22

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,

相关标签:
4条回答
  • 2020-12-01 06:45
    result = db.objects.insert_one(
       {"last_modified": datetime.datetime.utcnow()})
    

    Here utc stands for Universal Time Coordinates.

    0 讨论(0)
  • 2020-12-01 06:56

    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).

    0 讨论(0)
  • 2020-12-01 07:00

    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")
    }
    
    0 讨论(0)
  • 2020-12-01 07:03

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

    0 讨论(0)
提交回复
热议问题