1

I have a point feature class in ArcGIS desktop. There is a timestamp column named TS in datetime format in the attribute table.

I need to calculate and write time differences of rows from previous rows to a new column named RowDiff. Results will be in "seconds". RowDiff datatype is short integer.

I've found these links but I have no idea about implementing the functions:
https://desktop.arcgis.com/en/arcmap/latest/analyze/arcpy-time/esritimedelta-class.htm
https://www.programiz.com/python-programming/datetime

I've found the following code but results are in string format like 0:00:06.00005 and useless for me. What I need is row differences in seconds and an integer data type, not decimals.

import arcpy

from arcpy import da

gpsdata = arcpy.GetParameterAsText(0)  

#set firstRow variable to true
firstRow = True

with arcpy.da.UpdateCursor(gpsdata, ["OBJECTID", "TS", "D_T"]) 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)

Sample results should be as follows:

sapmle result

0

1 Answer 1

2

It's important to understand that Esri didn't create the datetime object used to transmit this information -- This is a fundamental Python datatype. The Python documentation covers the timedelta that results from datetime subtraction.

The difference in seconds (timedelta.total_seconds()) is a float value because the datetime type supports milliseconds (though ArcPy doesn't use them), but you can cast (or round) to int if you want to.

Your code has more complexity than is necessary. I'd do the following:

import arcpy

gpsdata = arcpy.GetParameterAsText(0)  

prev = None
with arcpy.da.UpdateCursor(gpsdata, ["OBJECTID", "TS", "D_T"]) as cursor:
    for row in cursor:
        tval = row[1]
        if (prev):
            row[2] = int((tval - prev).total_seconds())
        else:
            row[2] = None # could be zero
        cursor.updateRow(row)
        prev = tval

It might be wise to specify an ORDER BY so that your TS values are only increasing. Note that you can change the correct undefined (None) value to zero if you want.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.