Skip to content Skip to sidebar Skip to footer

Program To Work Out An Age Gives Error About A Getset_descriptor?

I am trying to write a very simple Python program to work out someone's age and I think, in theory, it should work however every time I try to run it, it throws this error: What y

Solution 1:

year = datetime.year does not give you the current year. It gives you an unbound descriptor object instead (the getset_descriptor in your error):

>>> datetime.year
<attribute 'year' of 'datetime.date' objects>
>>> type(datetime.year)
<class 'getset_descriptor'>
>>> datetime.year - 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'getset_descriptor' and 'int'

Don't worry too much about the exact type of object here, that's just an implementation detail needed to make instances of a built-in immutable type like datetime work. It just means you don't have an instance of the datetime type, so there is no year value for that instance either.

If you want the current year, use datetime.now().year:

year = datetime.now().year

datetime.now() gives you a datetime instance, the one representing the current time and date. That instance has a valid year attribute.

You could also use datetime.date.today() of course:

>>> from datetime import datetime, date
>>> datetime.now()
datetime.datetime(2016, 12, 31, 14, 58, 14, 994030)
>>> datetime.now().year
2016
>>> date.today().year
2016

Post a Comment for "Program To Work Out An Age Gives Error About A Getset_descriptor?"