user17338
user17338

Reputation: 133

How can I subtract today's datetime from a list of datetimes to find people's age?

I started with a list of birthdays that look like this: 01/01/1900 and I've named dob. I want to calculate their current age in years by subtracting the current time. So I did the following:

from datetime import datetime

parsed_date = [datetime.strptime(x, '%m/%d/%Y') for x in dob]
now = datetime.now()

age = now - parsed_date

parsed_date is a list made up of

[datetime.datetime(1984, 11, 11, 0, 0),
 datetime.datetime(1980, 10, 2, 0, 0),
 datetime.datetime(1991, 5, 13, 0, 0),
 datetime.datetime(1982, 8, 28, 0, 0), ... ]

Unfortunately for the age I get the following error:

TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'list'

I don't understand why this error pops up if it looks to me like I'm subtracting two datetimes to get a timedelta. If I do individually

now - datetime(1984, 11, 11, 0, 0)

then it works, but if I do

now - datetime.datetime(1984, 11, 11, 0, 0)

I get this error:

AttributeError: type object 'datetime.datetime' has no attribute 'datetime'

Upvotes: 2

Views: 2358

Answers (1)

Patrick Collins
Patrick Collins

Reputation: 10574

Instead of this:

age = now - parsed_date

Use this:

ages = [now - date for date in parsed_date]

Upvotes: 4

Related Questions