I would like to query a feature classes date range. For instance, if there is data within a 2 day range then I would like to print true or do something else. I thought arcpy.Exist would do the job, but I am missing something here. I guess my arcpy.Exist is only seeing if the variable exists, how would I check to see if the actual where clause is True for my feature layer?

query = arcpy.MakeFeatureLayer_management(fc, "QueryLayer", """Date BETWEEN '2014-02-16 16:53:25' AND  '2014-02-17 18:53:25'""")


    if arcpy.Exists(query):
        print "true"
        print "no data"

arcpy.Exists() will check for the existence of datasets, so it should always return true given the way you have it set up here, because query will exist whether there are records in it or not.

You could use arcpy.GetCount_management().

query = arcpy.MakeFeatureLayer_management(fc, "QueryLayer", """Date BETWEEN '2014-02-16 16:53:25' AND  '2014-02-17 18:53:25'""")
count = arcpy.GetCount_management(query).getOutput(0)
if count > 0:
    #do something: at this point you know that the query returned at least one record.

Based on @nmpeterson's answer in this post, you may want to try this alternative method for getting the count (if you're using 10.1+), may be faster:

count = sum((1 for row in arcpy.da.SearchCursor(query, ['OID@'])))
| improve this answer | |
  • Hi Mr. Adam, what is "OID@" I am not understanding this syntax. I figured a search cursor would be quicker as I don't need a feature layer. – Geoffrey West Apr 6 '15 at 14:30
  • "OID@" is the standard way to get the object ID field with the .da cursors. In this case, the cursor only includes one field, "OID@" and it is a field that is guaranteed to exist in every feature class or shapefile. So this sum operation is performed on a list of 1's, as many 1's as there are rows in the cursor, i.e. records in the feature class. More info on using OID@: resources.arcgis.com/en/help/main/10.1/index.html#//… – mr.adam Apr 6 '15 at 14:50

This solution works better.

cursor = arcpy.SearchCursor(fc,"""Date BETWEEN '2014-02-16 16:53:25' AND  '2015-02-17 16:53:25'""" )
for row in cursor:

if row.getValue("Date") < datetime.datetime.now():
    print "true"
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.