Error 'str' object has no attribute 'toordinal' in asyncpg

Question:

My queries were giving strange results so i debugged a little bit, i change my String, date object to sqlalchemy Date so it raised this error

asyncpg.exceptions.DataError: invalid input for query argument $2: '2020-03-11'
('str' object has no attribute 'toordinal')

Here is my sqlalchemyTable

db = sqlalchemy.Table(
"db",
metadata,
sqlalchemy.Column("date", Date),
sqlalchemy.Column("data", JSONB),
)

how i insert values:

query = db.insert().values(
    date=datetime.strptime(key,"%d/%m/%Y").strftime("%Y-%m-%d"),
    data=value,
)
try:
    await database.execute(query)
except UniqueViolationError:
    pass

Why did i change the type String to Date,because when i ran a query like

query = f"""SELECT * FROM db WHERE date BETWEEN SYMMETRIC '{start_at}' AND '{end_at}'"""
return await database.execute(query)

It was only returning one row and one column like 2020-03-11

Asked By: Yagiz Degirmenci

||

Answers:

I would say your issue is here:

date=datetime.strptime(key,"%d/%m/%Y").strftime("%Y-%m-%d"),

You are passing a string to a date field. SQLAlchemy is looking for a date object to be passed in, hence the ('str' object has no attribute 'toordinal') error. toordinal being an attribute of a date object. Remove the .strftime("%Y-%m-%d") and it should work.

Answered By: Adrian Klaver