Search code examples
pythonmongodbdatetimenonetypedate-math

What's the correct None or null entry for a datetime.datetime object in Python?


I'm loading some dates into mongodb using pymongo. Because pymongo does automatic conversions to BSON, I'm working with datetime's datetime.strptime function to turn input strings like "12/04/2013" into Date objects like so:

>>> datetime.datetime.strptime("12/04/2013",'%m/%d/%Y')
datetime.datetime(2013, 12, 4, 0, 0)

So that they can be searchable using standard mongo queries.

My problem is: I would also like to represent that I do not know what date something is in a way equivalent to None, so that I can do None null-tests on it. I realize I could just put this date very far in the past or future with a try-catch block for entering '' or None, but this is hacky thinking and I'd rather use a proper None-type to represent what is actually a None.

How can I enter a None datetime?


Solution

  • When you search MongoDB null and missing values are equivalent.

    > db.foo.insert({a: null})
    > db.foo.insert({})
    db.foo.find({a: null}, {_id: 0})
    { "a" : null }
    {  }
    

    It works the same way with pymongo:

    >>> [doc for doc in pymongo.MongoClient().test.foo.find({'a': None}, {'_id': 0})]
    [{u'a': None}, {}]
    

    So None seems to be a good choice. It is consistent with Python semantics, it plays nice with default behavior of dict.get method and maps intuitively to MongoDB types when using Python driver.