# ArcGIS calculate difference between rows in the same field that is date time format

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[1] row[2] = 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 atgap1=0) from a datetime object in the following line:row[2] = 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[1] #check if its the first row if firstRow == True: gap1 = gap2 #set firstrow to false firstRow = False continue row[2] = 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 as1 day).

I was curious if there was a cleaner way to use cursors without having to always use thefirstRowcheck, and it turns out the following works. Hooray for generators*!

with arcpy.da.SearchCursor(fc, "[email protected]") as cursor: p = cursor.next()[0] #previous for row in cursor: c = row[0] #current print(c - p) #function goes here to update values p = row[0] #becomes previous next iteration

Without knowing what your data looks like or how you want theGapDifffield populated (string, int, date, etc.), you'll need to come up with a function.

*Sincecursoris a generator,next(cursor)also works, as does calling the.reset()method on it to start from the beginning.