sqlalchemy.exc.StatementError with datetime field #1007
-
First Check
Commit to Help
Example Codefrom sqlmodel import SQLModel, Field, Session, create_engine
from datetime import datetime
class MyModel(SQLModel, table=True):
rowid: int | None = Field(default=None, primary_key=True)
timestamp: datetime
# Create an instance with a float (Unix timestamp)
instance = MyModel(timestamp=1625097600.0)
# Check the type and value
print(type(instance.timestamp)) # <class 'float'>
engine = create_engine("sqlite:////tmp/database.db")
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
session.add(instance)
session.commit() Description
This throws the following error:
Operating SystemLinux Operating System DetailsArch Linux SQLModel Version0.0.19 Python VersionPython 3.12.3 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
While initializing the instance, you provided a float to the timestamp field. You need to pass a datetime object. timestamp = 1625097600.0 This is because the type of the timestamp field is datetime. Hence it must be provided a datetime object |
Beta Was this translation helpful? Give feedback.
-
Found the answer in the source code. To finalize the pydantic validation, I needed to call from sqlmodel import SQLModel, Field, Session, create_engine
from datetime import datetime
class MyModel(SQLModel, table=True):
rowid: int | None = Field(default=None, primary_key=True)
timestamp: datetime
# Create an instance with a float (Unix timestamp)
instance = MyModel(timestamp=1625097600.0)
validated_instance = MyModel.model_validate(instance) # <----- THIS LINE FIXES IT
# Check the type and value
print(type(instance.timestamp)) # <class 'float'>
print(type(validated_instance.timestamp)) # <class 'datetime.datetime'>
engine = create_engine("sqlite:////tmp/database.db")
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
session.add(validated_instance)
session.commit() |
Beta Was this translation helpful? Give feedback.
Found the answer in the source code. To finalize the pydantic validation, I needed to call
model_validate()
: