Home > front end >  TypeError: descriptor 'isoformat' for 'datetime.date' objects doesn't apply
TypeError: descriptor 'isoformat' for 'datetime.date' objects doesn't apply

Time:06-06

I'm doing a university project in Python, I need to import from a JSON a string in the format of datetime.date that would be "YYYY-MM-DD", I was testing in a short program and I had no problems, but when entering in my general code it gave me this error

dt = date.isoformat(info["start_date"])

CodePudding user response:

This error message (admittedly not a very helpful one) implies you've tried to call on the type datetime.date directly, rather than an instance of it.

>>> from datetime import date
>>> date.isoformat("something")
TypeError: descriptor 'isoformat' for 'datetime.date' objects doesn't apply to a 'str' object

Instead it expects to be called as a method, without any arguments:

>>> date.today().isoformat()
'2022-06-05'

However, after reading your question it looks like you actually want to go the other way, parsing from a string into a date instance:

>>> date.fromisoformat("2022-06-05")
datetime.date(2022, 6, 5)

CodePudding user response:

You're trying to convert a string date to string date again which does not makes sense.

datetime.isoformat() takes a date as an argument, and converts it into a datetime object.

For example, let's consider this.

print(datetime.date.isoformat(datetime.now()))
>>> 2022-06-05

If you try to print datetime.now() you will see it returns a date instead of a string. So in above, .isoformat takes a date as an argument, then converts it into an iso string

So if you pass a string an argument here, code will surely crash, because it is expecting a date instead.

You need to use .fromisoformat() to convert strings to dates.

To give you an example, this code prints current date in every computer.

import datetime
today_in_iso_format = datetime.date.isoformat(datetime.datetime.now()) 
print(datetime.date.fromisoformat(today_in_iso_format))
  • Related