[GIS] Using where clause to query date ranges in ArcPy

arcpy

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'""")


try:
    query

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

Best Answer

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@'])))
Related Question