Khushboo Patel
Khushboo Patel

Reputation: 111

how to get datetime type column data into 'MM/YYYY' format using flask SqlAlchemy in python

I have an column in the database which is datetime type and i have to retrieve date into 'MM/YYYY' format.

what i have to do this in sqlalchemy, python?

my current query is as follow =>

session.query(Model.models.DefineStructureOfTable.Detail.AsOfDate).filter( Model.models.DefineStructureOfTable.Detail.ID.in_(getId)).all()

currently it gives me result as datetime type date

Please Help!

Upvotes: 0

Views: 3578

Answers (1)

blueteeth
blueteeth

Reputation: 3555

If your question is how to convert datetime into the format MM/YYYY, you can use strftime.

result.strftime("%m/%Y")

If your question is about how you make the database return a different format, you can't. You can't change the types of the underlying database. But you could change the type to TEXT, and just store the string directly - not recommended in this format because it will be hard to sort.

Alternatively add a method or property to the model to get the datetime in the right format.

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    month_and_year = db.Column(db.DateTime)
    
    @property
    def formatted_month_and_year(self):
        return self.month_and_year.strftime("%m/%Y")

Upvotes: 2

Related Questions