Select to view content in your preferred language

Calculate field conditional statement using a date formula

7438
11
Jump to solution
02-09-2016 10:25 PM
MoyaCalvert
New Contributor II

Hi all,

I am using ArcGIS 10.3 to update a field with a numeric value that represents the elapsed time since the data was captured.  I can do this in a python script that I have attached to a model but I also want to be able to sometimes do it quickly from within ArcGIS desktop and I am stumped.

I have written a 3 step process:

1. Create an integer field then calculate the number of days since today (field name = ET):

In Field Calculator, ET =

(datetime.datetime.now() - arcpy.time.ParseDateTimeString(!ActivityDate!)).days

2.  Create a conditional Statement for "Elapsed Time" field as follows:

Expression:

Reclass(!ET!)

def Reclass(ET):

    if ( ET < 28):

        return 1

    elif ( ET>= 28 and ET < 91):

        return 2

    elif ( ET >= 91 and ET < 182):

        return 3

    elif ( ET >= 182 and ET < 365):

        return 4

    elif (ET >= 365):

        return 5

3. Delete the ET field

I really just want to declare a variable in my conditional statement for ET which would save having to create then delete the ET field, but everything I have tried does not work, for example:

Expression:

Reclass(ET)

ET = (datetime.datetime.now() - arcpy.time.ParseDateTimeString(!ActivityDate!)).days

def Reclass(ET):

    if ( ET < 28):

        return 1

etc etc

I cannot find any examples of conditional statements that use a variable instead of a field value in the Field Calculator, so any help would be appreciated.

0 Kudos
11 Replies
DanPatterson_Retired
MVP Emeritus

Moya ... et al...

For future reference

Using either numpy or the bisect module makes things much simpler when trying to do a sequential value reclassification ... whether it be text or numbers.  Some thoughts and brief tests, before put into functions.

dts = [1,28,29,91,92,182,183,365,366]
bins = [28,91,182,365,400]

#1

import numpy as np
c = np.digitize(dts, bins, right=True) + 1

result    list(c) = [1, 1, 2, 2, 3, 3, 4, 4, 5]

#2

import bisect   
d = [ bisect.bisect_left(bins,i) + 1  for i in dts]

results  ditto

If these were put into a function they could do the reclassification for you.

In the examples here, a value of 1 was added to the returned indices to produce your new classification scheme.

The example #2 could be modified to turn it into a generator from a list comprehension.

I will post more on my blog when I get some more time and report back here.  These nested, multilevel if, else if, adnauseum, else statements have to go .

DanPatterson_Retired
MVP Emeritus

The final link with code blocks using numpy and bisect modules

List comprehensions 3 ...

if - elif - elif - elif - else  free examples