chris.stckhmr chris.stckhmr - 2 years ago 89
Python Question

SQLAlchemy: How to convert a value of a colum in ORM-class

I'm using SQLAlchemy do read from a (given) SQLite database. Unfortunately the time value is String and not a TIMESTAMP like "Fri Apr 15 15:57:59 2016"

class Test(Base):
__tablename__ = 'test'
id = Column('id', String, primary_key=True)
time = Column('id', String)

Is there a way to convert/map instant, so that class.time returns a datetime object ?

Answer Source

I would recommend throwing a property on top of your model:

from datetime import datetime

class Test(Base):
    __tablename__ = 'test'
    id = Column('id', String, primary_key=True)
    _time = Column('time', String)

    def time(self):
        return datetime.strptime(self._time, '%Y-%m-%d %H:%M')

Of course, you'll have to make sure that the format for strptime is appropriate. But this way you'll be able to call .time and get the appopriate timestamp.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download