# Calculate age function

5766
8
09-30-2015 08:43 AM
by
Regular Contributor

Does anyone have a python code block that calculates age based on a date field within a table?  I have tried a few different things but to no success.  Was wondering if someone has successfully done this?

Thanks!

1 Solution

Accepted Solutions
Esri Esteemed Contributor

Try replacing the today variable with 'today = datetime.now( )'.  Ex:

`from datetime import datetimedef calculate_age(born):    today = datetime.now( )    bornDate =datetime.strptime(born, '%m/%d/%Y')    return today.year - bornDate.year - ((today.month, today.day) < (bornDate.month, bornDate.day))`
8 Replies
MVP Frequent Contributor

Use a timedelta.  It should work for seconds, days, weeks, months, years, etc...  Easiest example I found is below.  Just get your minimum and maximum dates in the field/table and determine the difference.

http://stackoverflow.com/questions/1345827/how-do-i-find-the-time-difference-between-two-datetime-ob...

by
Regular Contributor

James,

If I try finding the difference between today's date and the date in my field, I get an error: unsupported operand type(s) for: 'datetime.date' and 'unicode'.  Is there a way to format the date field to something other than unicode?

Below is the function I have now.  The field I'm passing in for 'bday' is a Date field within a file gdb.

`import datetimedef calcAge(bday):  today = datetime.date.today()  diff = today - bday  return diff`
MVP Frequent Contributor

Welcome to the wonderful world of date manipulation!

Esri Esteemed Contributor

Hi Matthew,

Here is one option using the field calculator.  The below example worked when I had the date in the format: 8/15/2010.

`from datetime import datetimedef calculate_age(born):    today = date.today()    bornDate =datetime.strptime(born, '%m/%d/%Y')    return today.year - bornDate.year - ((today.month, today.day) < (bornDate.month, bornDate.day))`

by
Regular Contributor

When I try your method, I get an error: 'global name 'date' is not defined'.

Esri Esteemed Contributor

Try replacing the today variable with 'today = datetime.now( )'.  Ex:

`from datetime import datetimedef calculate_age(born):    today = datetime.now( )    bornDate =datetime.strptime(born, '%m/%d/%Y')    return today.year - bornDate.year - ((today.month, today.day) < (bornDate.month, bornDate.day))`
by
Regular Contributor

Thanks Jake Skinner​!  This worked

MVP Honored Contributor

I know this is in the Python section, but if all you need is number of days, VBScript handles it much easier (below is for shapefile, but should work similarly for GDB):

`Now (  ) - [YOURDATE]`

or years:

`CInt((Now (  ) - [YOURDATE])/365)`