Reputation: 31
I'm trying to find out the age of a person in 'days' by taking away 'current date' from 'birth date'.
For example, on python I could successfully use this code:
from datetime import date
date1 = date(2021, 7, 16)
date2 = date(2021, 8, 20)
numberDays = d1 - d0
print(numberDays.days)
Output:
35 days old.
But when I try to find out the 'current' date using datetime:
from datetime import datetime
birth = datetime(2021,8,19)
current = datetime.today().strftime('%Y, %m, %d')
age = (current - birth)
Output 2:
age = (current - birth) TypeError: unsupported operand type(s) for -: 'str' and 'datetime.datetime'
I'm not very sure what data type to convert the two variable into to get the same desired result as the first example code.
Thank you in advance.
Upvotes: 1
Views: 872
Reputation: 49
When you subtract one datetime object from another, you get an object of type "datetime.timedelta". From this type you can access to many properties and methods.
See here : https://docs.python.org/3/library/datetime.html
Therefore, to take your example :
import datetime as dt
birth = dt.datetime(2020, 8, 20)
# Substract the date (the result has the type datetime.timedelta)
age = dt.datetime.today() - birth
# show the days property
print(age.days)
Your error message comes from the fact you try to substract a datetime object from a string.
because:
current = datetime.today().strftime('%Y, %m, %d')
is a string (string from a time)
Upvotes: 1