I have a shapefile of point features showing fire locations in a given year. One of the fields is named "YYYYMMDD" and indicates the corresponding date that that fire happened. In Python, I am trying to use the arcpy.da.SearchCursor function to append each date into a list and find the most recent fire by date.
My code looks like this:
listname = []
cursor = arcpy.da.SearchCursor(fires, "YYYYMMDD")
for row in cursor:
listname.append(row)
print 'the first fire date is ',min(listname),'.'
print 'the last fire date is ',max(listname),'.'
What prints for min and max listname is: (20010515.0,) and (20011002.0,) But what I would like to get as an output is: 20010514 and 20011002
How do can I get that as my output?
I tried indexing what I got to exclude what I don't need but that doesn't work.
3 Answers 3
You need to grab the first element of each row and convert to int.
listname = []
cursor = arcpy.da.SearchCursor(fires, "YYYYMMDD")
for row in cursor:
listname.append(int(row[0]))
print 'the first fire date is {0}.'.format(min(listname))
print 'the last fire date is {0}.'.format(max(listname))
-
You may also want to utilize a
sql_clause
in your search cursor something likesqlClause = (None, ‘ORDER BY ‘ + "YYYYMMDD" + ‘ DESC’)
and then add that to your Search Cursor like this:cursor = arcpy.da.SearchCursor(fires, "YYYYMMDD", sql_clause = sqlClause)
. That way your field will already be sorted.GeoSharp– GeoSharp2014年05月08日 21:40:39 +00:00Commented May 8, 2014 at 21:40
try it like this:
In your cursor loop - change to:
listname.append(row[0])
and for your printing - change to:
print "The first fire date is {0}".format(min(listname))
print "The last fire date is {0}".format(max(listname))
you should note that, in your case, row is a list (even if there is only one field). so listname becomes a list of lists. you need to take the value out of your list.
listname = []
cursor = arcpy.da.SearchCursor(fires, "YYYYMMDD")
for row in cursor:
listname.append(row[0])
then you can format it as you want, e.g. :
print "the first date is " + str(min(listname))