4

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")
0

2 Answers 2

3

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
1

I would just find the difference in minutes between the date and a certain arbitrary date.

import arcpy
import datetime

fc = r"C:\GIS\Temp\test.gdb\FeatureClass"
with arcpy.da.UpdateCursor(fc,["date","dateint"]) as upd_c:
    for row in upd_c:
        january1st = datetime.datetime(2010, 01, 01)        
        timesince = row[0] - january1st
        minutessince = int(timesince.total_seconds() / 60)
        row[1] = minutessince
        upd_c.updateRow(row)

The larger the value the later date value is.

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.