Determine if an entity is created 'today'
<p>I am creating an app which, on any given day, only one entity can be created per day. Here is the model:</p>

<pre><code>class MyModel(ndb.Model):
    created = ndb.DateTimeProperty(auto_now_add=True)
</code></pre>

<p>Since only one entity is allowed to be created per day, we will need to compare the MyModel.created property to today's date:</p>

<pre><code>import datetime

class CreateEntity(webapp2.RequestHandler):
    def get(self):
        today = datetime.datetime.today()
        my_model = MyModel.query(MyModel.created == today).get()

        if my_model:
          # print("Today's entity already exists")
        else:
          # create today's new entity
</code></pre>

<p>The problem is that I cannot compare the two dates like this. How can I check if an entity was already created 'today'?</p>

<p>You can't query by <code>created</code> property using <code>==</code> since you don't actually know the <strong>exact</strong> creation datetime (which is what you'll find in <code>created</code> due to the <code>auto_now_add=True</code> option)</p>

<p>But you could query for the most recently created entity and check if its <code>creation</code> datetime is today. Something along these lines:</p>

<pre><code>class CreateEntity(webapp2.RequestHandler):
    def get(self):
        now = datetime.datetime.utcnow()
        # get most recently created one:
        entity_list = MyModel.query().order(-MyModel.created).fetch(limit=1)
        entity = entity_list[0] if entity_list else None
        if entity and entity.created.year  == now.year and \
                      entity.created.month == now.month and \
                      entity.created.day   == now.day:
            # print("Today's entity already exists")
        else:
            # create today's new entity
</code></pre>

<p>Or you could compute a datetime for today's 0:00:00 am and query for <code>created</code> bigger than that.</p>

<p>Or you could drop the <code>auto_now_add=True</code> option and explicitly set <code>created</code> to a specific time of the day (say midnight exactly) and then you can query for the datetime matching that time of day today.</p>

python google-app-engine datetime google-cloud-datastore app-engine-ndb