Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 225
Mittenchops Avatar asked Dec 04 '13 21:12

Mittenchops


People also ask

Does datetime accept NULL?

DateTime CAN be compared to null; It cannot hold null value, thus the comparison will always be false. DateTime is a "Value Type". Basically a "value type" can't set to NULL. But by making them to "Nullable" type, We can set to null.

What is the format of datetime in Python?

format is the format – 'yyyy-mm-dd'

How do I check if a datetime is NULL in Python?

Use model. myDate. HasValue. It will return true if date is not null otherwise false.


2 Answers

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.

like image 81
zero323 Avatar answered Oct 10 '22 19:10

zero323


MongoDB is a NoSQL database, meaning that you can make interesting data models.

http://docs.mongodb.org/manual/core/data-modeling-introduction/

Each document in your collection does not need to have the same set of field names. If you do not know the date, you may simply leave it out. Your application code can easily check the existence of of the timestamp when you want to retrieve the document

import pymongo
import datetime

mclient = pymongo.MongoClient()
mclient.test.example.insert({'Name': "Orange"})
mclient.test.example.insert({'Name': "Lemon", 'timestamp':datetime.datetime.now()})
for document in mclient.test.example.find():
    if "timestamp" in document:
        print document
like image 43
bauman.space Avatar answered Oct 10 '22 17:10

bauman.space