How can I create a function utilizing datetime?

can someone explain why can’t?

# import library
import datetime
# create functions
def calculate_age(date_of_birth, current_year):
    current_year = datetime.datetime.now() # from lib import
    age = (current_year - date_of_birth)
    return age

so after run the functions, i got this error

calculate_age(1984)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: calculate_age() missing 1 required positional argument: 'current_year'

even adding more argument

calculate_age(2019,1984)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in calculate_age
TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'int'

the function im creating is use datetime lib to always get current date. Thanks for explanation for solution :sweat_smile:

The second parameter should be removed since you are defining it inside the function.

Bear in mind that the output of now() is a datetime object…

>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2019, 10, 31, 10, 12, 58, 955612)
>>> datetime.datetime.now().year
2019
>>> 
1 Like

Thanks for the explanation will keep in my mind now() is an object.

1 Like