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:
|
SORT =
|
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.
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:
|
SORT =
|
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
).