I have extracted a series of dates from a database I am storing within a list. Like this:
query_age = db.select([customer.columns.dob])
proxy_age = connection.execute(query_age)
result_age = proxy_age.fetchall()
date = []
for row in result_age:
date.append(' '.join(row))
It comes down to looking like this: ['2002-11-03', '1993-08-25', '1998-01-30']
I have tried the following but it comes out very unpythonic:
ages = []
years = []
for row in y:
ages.append(''.join(row))
for i in ages:
years.append(int(i[:4]))
years_age = [int(x) for x in years]
print(years_age)
I figured with this I could just convert the given string to an integer and subtract from 2021 but it looks ugly to me.
I am trying to pass the items within the list to a function called 'age' which will determine the amount of elapsed time between the specific date and the present in years. I have tried datetime.strptime() but cannot figure it out. I am a very new programmer. Any help would be appreciated.
CodePudding user response:
Using the information from this post, you can create a function age like the one below. Note that fmt
is simply the format of your date string
import datetime
from dateutil.relativedelta import relativedelta
def age(dob, fmt = '%Y-%m-%d'):
today = datetime.datetime.now()
birthdate = datetime.datetime.strptime(dob, fmt)
difference_in_years = relativedelta(today, birthdate).years
return(difference_in_years)
Then, using the information from your post above:
DOB = ['2002-11-03', '1993-08-25', '1998-01-30']
for d in DOB:
print("DOB:%s --> Age: %i" % (d, age(d)))
# DOB:2002-11-03 --> Age: 18
# DOB:1993-08-25 --> Age: 28
# DOB:1998-01-30 --> Age: 23