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!
Solved! Go to Solution.
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))
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.
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
Welcome to the wonderful world of date manipulation!
I think Jake has your answer below.
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))
When I try your method, I get an error: 'global name 'date' is not defined'.
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))
Thanks Jake Skinner! This worked
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)