0

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.

  • 1
    Can you post the age function and show how you have tried using it? – norie Oct 11 '21 at 18:06
  • https://stackoverflow.com/questions/4436957/pythonic-difference-between-two-dates-in-years – ramzeek Oct 11 '21 at 18:27
  • @norie My age function is empty as of now, I am required to pass a string value to it and return an integer that represents the number of years between the given string and the present. I have tried stripping the string to the years and potentially converting to integer for analysis but it comes out very unpythonic in my eyes. I feel it should be simpler than what I am doing. – Arturo Altamirano Oct 12 '21 at 00:07

1 Answers1

1

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
ramzeek
  • 2,226
  • 12
  • 23