Select to view content in your preferred language

Python scripting in Field Calculator: String to Integer w/ Conditional Statement

2792
2
08-06-2010 06:12 AM
BradleyCabe
Deactivated User
Good day,

I've been having some issues writing a python script for a Field Calculation. The code I've written:

Pre-Logic Script Code:
yyyy = !DATE_LCL![4:]:

dd = !DATE_LCL![5,6]:

if !DATE_LCL![7,9] = 'Jan':
   mm = 01
elif !DATE_LCL![7,9] = 'Feb':
   mm = 02
else:
   mm = 99
end if


Field:
yyyy + mm + dd


This script is desigend to take a string field (DATE_LCL) of a standardized date (ex. Thu 15Jul2010) and convert it to the following integer format: yyyymmdd. The current code is only coverting from the initial format to the new format while retaining the string data type. Eventually, I'll be converting it into a short int.

While running the code, I get the 000989 error code which is an invalid syntax. While I have no doubt that my syntax is invalid, I'm sure my code has some more fundamental issues as well. Any help?
0 Kudos
2 Replies
DavidWynne
Esri Contributor
Hi,
I believe this is what you would want:

Expression:
convertDate(!DATE_LCL!)


Code block:
def convertDate(sdate):
    yyyy = sdate[-4:]
    dd = sdate[4:6]
    if sdate[6:9] == 'Jan':
        mm = "01"
    elif sdate[6:9] == 'Feb':
        mm = "02"
    else:
        mm = "99"
    return yyyy + dd + mm



Basically, you need to create a Python function in the code block (this is the def), and call that function from the expression.  The use of ! for delimiters is something that you use only in the expression--it is just a way of passing a field value down to the function.  In the function, you assign the incoming value a variable name, in this case sdate.

It easy to test these directly in Python.  If you created a new Python script, add this function above in the top, and add an additional line, something like...

newdate = convertDate("Thu 15Jul2010")
print newdate


... this will give you a very quick idea if your code is working (and if not, will be easy to debug).

-Dave
0 Kudos
BradleyCabe
Deactivated User
FANTASTIC!

Thank you. Not only did you solve this issue, you also taught me something about python! 😄
0 Kudos