I'm looking for help tweaking the python code discussed here: Attribute Table Subtract Value From Previous Value
I'm having trouble figuring out how to adjust it for a date field in which I want to subtract a time by the previous time to get gaps. Here is what I have so far and the error received:
import arcpy from arcpy import da vertices ="CBR05_T2_10_1_2014_WLanduse_1" gap1=0 with arcpy.da.UpdateCursor(vertices, ["INDEX_", "Time", "GapDiff"]) as cursor: for row in cursor: gap2 = row row = datetime(gap2 - gap1) gap1 = gap2 cursor.updateRow(row)
Runtime error Traceback (most recent call last): File "", line 8, in TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'int'
You're trying to subtract an integer (defined at
gap1=0) from a datetime object in the following line:
row = datetime(gap2 - gap1). You'll need to skip the first row and assign its datetime to a variable for the next row. Since the first row has no proceeding datetime, it won't get a value updated.
This worked for me:
import arcpy from arcpy import da vertices ="CBR05_T2_10_1_2014_WLanduse_1" #set firstRow variable to true firstRow = True with arcpy.da.UpdateCursor(vertices, ["INDEX_", "Time", "GapDiff"]) as cursor: for row in cursor: gap2 = row #check if its the first row if firstRow == True: gap1 = gap2 #set firstrow to false firstRow = False continue row = str(gap2 - gap1) gap1 = gap2 cursor.updateRow(row)
Note that the "GapDiff" field needs to be a string field. a datetime field doesn't support time values resulting from a subtration (such as
I was curious if there was a cleaner way to use cursors without having to always use the
firstRowcheck, and it turns out the following works. Hooray for generators*!
with arcpy.da.SearchCursor(fc, "[email protected]") as cursor: p = cursor.next() #previous for row in cursor: c = row #current print(c - p) #function goes here to update values p = row #becomes previous next iteration
Without knowing what your data looks like or how you want the
GapDifffield populated (string, int, date, etc.), you'll need to come up with a function.
cursoris a generator,
next(cursor)also works, as does calling the
.reset()method on it to start from the beginning.