Jonathan Petitcolas
Jonathan Petitcolas

Reputation: 4574

SQL Alchemy - Setting datetime as a string and getting a date?

I'm currently setting up a class using SQL Alchemy. This class has a start_date attribute, defined such as:

from sqlalchemy import Column, DateTime
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Foo(Base):
    __tablename__ = "foo"

    id = Column(UUID(as_uuid=True), primary_key=True)
    start_date = Column(DateTime, nullable=True)

Yet, I'm facing a type issue:

foo = Foo(start_date="2019-05-05")
print(foo.start_date, type(foo.start_date))

# 2019-05-05 <class 'str'>

I would expect a datetime here, especially as when fetching the same record from the database, I retrieve a date time object:

foo = Foo(id=uuid.uuid4(), start_date="2019-05-05")
db_session.add(foo)
db_session.commit()

db_session.refresh(foo)
print(foo.start_date, type(foo.start_date))

# 2019-03-01 00:00:00 <class 'datetime.datetime'>

Is there any way to force a cast from the Column declaration?

Upvotes: 1

Views: 5334

Answers (1)

Kendas
Kendas

Reputation: 2243

I suspect what's happening here is you're actually accessing in the first snippet is the very string you passed as the start_date keyword argument. This would suggest that SQLAlchemy does not actually coerce the type of your input.

When the object is committed to the database, this string ('2019-05-05') is passed to Postgres. Since SQL does type casting on quoted values, and this is in the correct format, it is added to the database as a timestamp.

After the insert the whole row is read from the database. This would return a datetime instance and the attribute would be set to a datetime value.

Keep in mind that this is partly conjecture on my part and I haven't actually looked up the way SQLAlchemy handles the input values.

Upvotes: 1

Related Questions