1

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"
asked Apr 6, 2015 at 14:06
1

2 Answers 2

3

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@'])))
answered Apr 6, 2015 at 14:17
2
  • 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. Commented Apr 6, 2015 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#//… Commented Apr 6, 2015 at 14:50
1

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:
 print(row.getValue("Date"))
if row.getValue("Date") < datetime.datetime.now():
 print "true"
answered Apr 6, 2015 at 15:02

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.