0

I need to set default time to now but don't want the time to appear. How could I set the default timestamp with only the date, and exclude the time?

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, index=True)
    email = db.Column(db.String(64), unique=True, index=True)
    password = db.Column(db.String(128))
    # phone = db.Column(db.String(16), unique=True, index=True)
    bio = db.Column(db.String(64))
    create_time = db.Column(db.DateTime(64), default=datetime.utcnow)
Christopher Peisert
  • 21,862
  • 3
  • 86
  • 117
Grace Pan
  • 21
  • 3

2 Answers2

0

As explained in Jeff Widman's answer to the question SQLAlchemy default DateTime, it is a best practice to have the database server calculate the default datetime rather than the application server. This is accomplished with the SQLAlchemy func.now().

from sqlalchemy.sql import func

class User(db.Model, UserMixin):
    ...
    create_time = db.Column(db.DateTime(timezone=True), default=func.now())

Then to display only the date portion of the datetime, you can format the datetime fields in your application, such as when rendering templates.

See How do I format a date in Jinja2?

Filter query by date

You can also filter your query using just the date.

from datetime import datetime

users = User.query.filter(User.create_time >= datetime.today()).all()
Christopher Peisert
  • 21,862
  • 3
  • 86
  • 117
0

I found a simple solution, I just modify the HTML page like this:

{{ data.create_time.strftime('%Y-%m-%d %H:%M:%S') }}
Grace Pan
  • 21
  • 3