[GIS] Transforming ArcGIS date field to integer

arcgis-desktoparcpydatefield-calculator

I have a featureclass with a 'date' class field named 'ACQ_DATE' formatted as:

1-8-2013
24-7-2013

etc. As you can see the number of digits is not harmonized. I want to display the dates on a graduated colour scale in the symbology (i.e. earliest date: red, latest date: green), but I understand that graduated colours are not applicable to a date field. Therefore, I want to transform the date to an integer which is supported by graduated colours. The integer should be in the format:

20130801
20130724

I've tried the following python code block, but it doesn't work.

date=str(!ACQ_DATE!)
year= date.split("-")[2]
month= date.split("-")[1]
day= date.split("-")[0]
dateInt= year * 10000 + month * 100 + day

This code gives a syntax error, but I'm not sure what's wrong with it.

How do I convert a date field to an integer field?


A good solution was provided by a colleague. Write in the calculator:

datetime.datetime.strptime(str(!ACQ_DATE!), "%d-%m-%Y").strftime("%Y%m%d")

Best Answer

I suggest that you use strftime('%Y%m%d') in the field claculator.

Just for the sake of completeness, your method is not very "pythonic" but it seems correct. However,the wrapping of your python code block as shown on your post looks incorrect. Unlike with VB, you need to define a fucntion in the code block, and call it in the field calculator.

code_block_function(!ACQ_DATE!)

in the code block, use:

def code_block_function(a):
    date=str(a)
    year= date.split("-")[2]
    month= date.split("-")[1]
    day= date.split("-")[0]
    dateInt= int(year) * 10000 + int(month) * 100 + int(day)
    return dateInt
Related Question