16
class Posts(Base):
    __tablename__ = 'posts_posts'
    id = Column(Integer, primary_key = True)
    user_id = Column(Integer, nullable=False)
    body = Column(Text, nullable=True)

    created_at = Column(Date) << is this right?
    updated_at = Column(Date) ??

I would also like the created_at column to automatically set the date when it's created. And also, the updated_at column to set the date anytime this row is changed.

1 Answer 1

29

You can provide default and onupdate parameters to Column:

def _get_date():
    return datetime.datetime.now()

class Posts(Base):
    #...
    created_at = Column(Date, default=_get_date)
    updated_at = Column(Date, onupdate=_get_date)

See Column documentation for more info on this one.

Sign up to request clarification or add additional context in comments.

3 Comments

There's even easier way: updated_at = Column(Date, onupdate=datetime.datetime.now)
Any tips to how to make datetime.datetime.now() timezone aware in SQL Alchemy context?
@MikkoOhtamaa: sqlalchemy.types.Datetime takes a parameter timezone with default value of False.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.