Leaves One

Alan Richard's Blog

Numbering Features in Chronological Order with ArcGIS Desktop

Problem

I have a feature class with a datetime field (named “TIME”), and I want to add an index field that contains the order of the features by time (ascending).

First Attempt

SORT field is appended to the feature class.

Initially, I tried to use the following code in Field Calculator (source: https://support.esri.com/en/technical-article/000018847)

Pre-logic Script Code:

rec = 0

def autoIncrement():
global rec
pStart = 1
pInterval = 1
if (rec == 0):
rec = pStart
else:
rec += pInterval
return rec

SORT =

autoIncrement()

First attempt

The problem is that the SORT field is not in the correct order. It is in the order of the features in the feature class, not in the order of the time field.

First attempt result

Reason

The reason is that Field Calculator fills the field in the feature class order, not in the time order (even with features sorted in the Attribute Table).

In order to index features by time, we need to figure out the new order of the features, and then fill the SORT field with the new indices.

Solution

The solution is to use arcpy.Sort_management to sort the features by time, and then use arcpy.CalculateField_management to fill the SORT field with the new indices.

Pre-logic Script Code:

feature_class = r'C:\path\to\shapefile.shp'  # <== change this to your feature class's path!

time_field_name = 'TIME' # <== change 'TIME' if your time field is named differently


def str_to_timestamp(text):
return time.strptime(str(text), "%Y-%m-%d %H:%M:%S")

fid_time = []

with arcpy.da.SearchCursor(feature_class, ['FID', time_field_name]) as cursor:
for row in cursor:
fid_time.append((row[0], str_to_timestamp(row[1])))

# sort by time
fid_time.sort(key=lambda x: x[1])

fid_sorted_index = {}

for i in range(len(fid_time)):
fid_sorted_index[fid_time[i][0]] = i

SORT =

fid_sorted_index[!FID!]

Final result

Notes

The new indices are 0-based. If you want 1-based indices, you can add 1 to the result of fid_sorted_index[!FID!] (i.e. fid_sorted_index[!FID!] + 1).

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
If you checked “Remember me”, your email address and name will be stored in your browser for your convenience.