I have created a python function within field calculator to calculate the time difference between a timestamp (yyyy-MM-dd HH:mm:ss) in a row and the row after (the interval field in seconds). I have used a update cursor with field calculator to do this, however I am receiving null values for both the first and last row.
The first is correctly missed due to the function being reliant on having a value set by the previous row.
I am unsure as to why the last row is being skipped?
The first row of the attribute is formatted as:
The last:
I have had this issue on several other update cursor functions including those on simple single row condition statements.
Am I missing a statement to close the update cursor loop?
My code is:
import arcpy, time, datetime
from time import strftime
from datetime import timedelta, datetime
from arcpy import da
def FindTime(table,date,interval):
firstRow = True
with arcpy.da.UpdateCursor(table, ["interval", "date"]) as cursor:
for row in cursor:
gap2 = row[1]
if firstRow == True:
gap1 = gap2
firstRow = False
continue
timedelta = gap2 - gap1
row[0] = timedelta.days * 24 * 3600 + timedelta.seconds
gap1 = gap2
cursor.updateRow(row)
*Updated from below comment's solution:
import arcpy
def FindTime(fc, datefield, daydiff_field):
all_dates = [i[0] for i in arcpy.da.SearchCursor(fc,datefield)]
diff = [(d1-d0).seconds for d0,d1 in zip(all_dates, all_dates[1:])]
givediff = iter(diff)
with arcpy.da.UpdateCursor(fc, daydiff_field) as cursor:
next(cursor) #uncomment this line if you want to calculate row2 diff as row2-row1, =first row no diff
for row in cursor:
try:
row[0] = next(givediff) #Fetch diffs until list is empty...
cursor.updateRow(row)
except StopIteration: #...then break the cursor
break