Select to view content in your preferred language

Calculate age in field calc using python parser

2432
4
Jump to solution
12-17-2012 07:48 AM
JustinNettleton
Deactivated User
I am looking to calculate an Age field from a DOB field using the python Parser in Desktop field calculator. Does anyone know the syntax I would need to use?

Thanks,
0 Kudos
1 Solution

Accepted Solutions
AndrewChapkowski
Esri Regular Contributor
Using the code box in field calculator, you can subtract two python datatime objects from each other.

For the code block use something like this:
def dateDiff(date):    from datetime import datetime    return int((datetime.now( ) - datetime.strptime(date,"%m/%d/%Y")).days/365.2425)


In the expression just enter in the name the following:
dateDiff( !DOB! )


Where field DOB is a date field.

View solution in original post

0 Kudos
4 Replies
AndrewChapkowski
Esri Regular Contributor
Using the code box in field calculator, you can subtract two python datatime objects from each other.

For the code block use something like this:
def dateDiff(date):    from datetime import datetime    return int((datetime.now( ) - datetime.strptime(date,"%m/%d/%Y")).days/365.2425)


In the expression just enter in the name the following:
dateDiff( !DOB! )


Where field DOB is a date field.
0 Kudos
JustinNettleton
Deactivated User
Thanks, works perfect.
0 Kudos
DanielO_Donnell
Deactivated User
This works very well, unless there is a NULL value in a record. Naturally, one doesn't always have a DOB for each record.

Any ideas?

I Add Field "Age", then Calculate Field using the above python algorythm... however, I get an error when it hits NULL values.

ERROR 000539:
Error running expression datediff ( " " ) <type 'exceptions.ValueError'>: time data ' ' does not match format '%Y%m%d'
Failed to execute (Calculate Field: AGE)
0 Kudos
LucasDanzinger
Esri Frequent Contributor
If you are at 10.1, you can just test to see if a value is Null by checking to see if it equals None. This is highlighted in KB 40913.

You should be able to do something like:

def dateDiff(date):
   from datetime import datetime
   if date is None:
       pass
   else:
       return int((datetime.now( ) - datetime.strptime(date,"%m/%d/%Y")).days/365.2425)
0 Kudos