Calculate age function

7141
8
Jump to solution
09-30-2015 08:43 AM
mpboyle
Occasional Contributor III

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!

0 Kudos
1 Solution

Accepted Solutions
JakeSkinner
Esri Esteemed Contributor

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

from datetime import datetime

def 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))

View solution in original post

8 Replies
JamesCrandall
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...

mpboyle
Occasional Contributor III

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 datetime

def calcAge(bday):
  today = datetime.date.today()
  diff = today - bday
  return diff
0 Kudos
JamesCrandall
MVP Frequent Contributor

Welcome to the wonderful world of date manipulation! 

I think Jake has your answer below.

0 Kudos
JakeSkinner
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 datetime

def 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))

screen1.PNG

mpboyle
Occasional Contributor III

Jake Skinner​,

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

0 Kudos
JakeSkinner
Esri Esteemed Contributor

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

from datetime import datetime

def 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))
mpboyle
Occasional Contributor III

Thanks Jake Skinner​!  This worked

DarrenWiens2
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)