[英]How to set the default timestamp with the date only (without the time)?
I need to set default time to now
but don't want the time to appear.我需要将默认时间设置为now
,但不希望时间出现。 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)
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.正如Jeff Widman对问题SQLAlchemy default DateTime的回答中所解释的,让数据库服务器而不是应用程序服务器计算默认datetime
时间是最佳实践。 This is accomplished with the SQLAlchemy func.now()
.这是通过 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.然后要仅显示datetime
的日期部分,您可以在应用程序中格式化datetime
字段,例如在呈现模板时。
See How do I format a date in Jinja2?请参阅如何格式化 Jinja2 中的日期?
You can also filter your query using just the date.您还可以仅使用日期来过滤查询。
from datetime import datetime
users = User.query.filter(User.create_time >= datetime.today()).all()
I found a simple solution, I just modify the HTML page like this:我找到了一个简单的解决方案,我只是像这样修改 HTML 页面:
{{ data.create_time.strftime('%Y-%m-%d %H:%M:%S') }}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.