Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 91,253 Points

Formatting the Datetime string with SQLAlchemy

Can I just say first of all I've been really enjoying the SQLAlchwemy and Flash content, and I've made a little website with it. and plan to do a bigger one in time.

I'm almost ready to deploy it somewhere, but there's just one little thing.

I'd like to be able to display a string format for the Datetime object that is used for one of my fields.

Here's the model I'm using.

 # Declare imports for the app
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import datetime


# Connect to SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///roster.db'

app.secret_key = "[SECRET KEY GOES HERE]"  # Secret key


db = SQLAlchemy(app)


# Create Database Model - 3 fields + ID as primary key
class Roster(db.Model):
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column("Name", db.String(80), unique=True, nullable=False)
    age = db.Column("Age", db.Integer, unique=True, nullable=False)
    joined = db.Column('Joined', db.DateTime, default=datetime.datetime.now)

    def __repr__(self):
        return f'''<Roster %r> ({self.name} 
        Age: {self.age}
        Joined: {self.joined }
       '''

which returns a string like 2021-09-09 15:44:15.817857 for that column. Is there a way to do this? The obvious answer would seem to me to be to use `strftime() instead rather than datetime.now but SQLAlchemy doesn't seem to support it.

Is there not a way to format it to something more readable? Thanks. :)

1 Answer

I don't know if you can specify the format of the datetime directly in SQLAlchemy.

You could create a method inside your Roster class to return the formatted datetime, and call that method instead of accessing joined from outside the class.

You could change joined into a db.String column and convert the datetime to a string of the correct format before storing in the model. This could lose some precision depending on the format of the string, since it would no longer be a datetime object. It would also require passing arguments to the strftime function without calling the function immediately. One way to do that would be to create a function outside the Roster class with no parameters that returns the string, and pass the reference to that function as the default value for joined.

Jonathan Grieve
Jonathan Grieve
Treehouse Moderator 91,253 Points

You possibly can. It's ideal though for capturing the moment the record was added though which is why it was originally done this way.

I'll have a look into your suggestions, thanks. :-)