[GIS] ArcGIS calculate difference between rows in the same field that is date time format

arcpyattribute-tabledatetimepython

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'

Best Answer

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

with arcpy.da.SearchCursor(fc, "OID@") 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 the GapDiff field populated (string, int, date, etc.), you'll need to come up with a function.

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