Skip to content

sqlalchemy.exc.StatementError with datetime field #1007

Closed Answered by TheTechromancer
TheTechromancer asked this question in Questions
Discussion options

You must be logged in to vote

Found the answer in the source code. To finalize the pydantic validation, I needed to call model_validate():

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/data…

Replies: 2 comments 4 replies

Comment options

You must be logged in to vote
3 replies
@TheTechromancer
Comment options

@20-buck-spin
Comment options

@TheTechromancer
Comment options

Comment options

You must be logged in to vote
1 reply
@TheTechromancer
Comment options

Answer selected by TheTechromancer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
2 participants