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!
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
Welcome to the wonderful world of date manipulation!
I think Jake has your answer below.
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)
Jake Skinner,
When I try your method, I get an error: 'global name 'date' is not defined'.
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
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))
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-objects-in-python
Signed in members can post, follow updates, and more. New here? Register a free account.
Find useful guides, FAQs, and documents to help you navigate and make the most of Esri Community.