[GIS] How to generate a list of unique years from date field

arcgis-10.1arcpycursor

I have data that was collected over many years and I'd like to be able to run a python script tool in ArcToolbox (ArcGIS 10.1) to get a list of unique years from the date field.

I found an example of how to format the date field, but this example lists the year from every record, and I just want a list of unique years.

# Imports
import arcpy
from datetime import datetime

# Input Table
fc = arcpy.GetParameterAsText(0)

# Date Field
field = arcpy.GetParameterAsText(1)

rows = arcpy.SearchCursor(fc)
for row in rows:
    datetimeVal = row.getValue(field)
    formattedTime = datetime.strftime(datetimeVal, "%Y")
    arcpy.AddMessage(formattedTime)

I can get a list of unique dates using a search cursor, but I just want the year and not the entire date field:

# imports
import arcpy
from datetime import datetime

# Input Table
inputTable = arcpy.GetParameterAsText(0)

# Date Field
field = arcpy.GetParameterAsText(1)

# Use SearchCursor with list comprehension to return a
#  unique set of values in the specified field
values = [row[0] for row in arcpy.da.SearchCursor(inputTable, (field))]
uniqueValues = set(values)
arcpy.AddMessage(uniqueValues)

How can I get the date in the example above, format it to just get the year, and then run the search cursor to get a list of unique years?

Best Answer

Here is one approach that uses the datetime module to parse the year from a datetime object. The SearchCursor is wrapped in a generator expression to extract unique years from the "date" field in the table.

import arcpy
from datetime import date

table = r'C:\path\to\your.gdb\table'

print set(date.strftime(row[0], "%Y") for row in arcpy.da.SearchCursor(table, "date"))

enter image description here

Result:

>>> 
set(['2008', '2009', '2011', '2022'])
Related Question