Search code examples
mongodbdatetimepymongoisodate

Would MongoDB take a datetime object with missing fields?


Right now I have a datetime object, but it doesn't contain all the fields. It's missing minutes, seconds, and microseconds. I want to use this to fetch data from MongoDB through Python. i'm just wondering if pymongo will automatically fill in the missing fields and convert it into ISODATE, or it's going to produce an error?

EDIT: an example:

time1='2015-12-17 23'
#assuming already imported all necessary libs
time2=datetime.strptime(time1, '%Y-%m-%d %H')
#for mongo
sq = {'$and': [something.some, {'field1':{'ne':1}}]}
sq['$and'].append({'field2': {'$gt': time2}})

Solution

  • In python, there's no such thing as a datetime object with missing fields. All the datetime fields (relevant to this question) always have values.

    The way you created time2, the fields you didn't specify get the value 0, as demostrated here:

    % time2
    => datetime.datetime(2015, 12, 17, 23, 0)
    % time2.minute, time2.second, time2.microsecond
    => (0, 0, 0)
    time2 == datetime(2015, 12, 17, 23, 0,0,0)
    => True
    

    As demostrated above, your time2 object is identical to the object you would have gotten if were manually filling the values with zeros.

    Now that you see your datetime object is not missing anything, it should be clear how mongodb treats it.