我想让我的代码对用户更加友好,这样当用户发布某些内容时,我希望它说“x秒/小时/天前”
到目前为止我的代码是
{{ post.date_posted.strftime('%Y-%m-%d %H:%M:%S') }}
datetime.timedelta()
import datetime
import time
old_time = datetime.datetime.now()
time.sleep(20)
new_time = datetime.datetime.now()
# The below line returns a 'timedelta' object.
delta = new_time - old_time
print('{} seconds have passed.'.format(delta.total_seconds()))
# or
print(
'{} days, {} hours, {} minutes, {} seconds passed.'.format(
delta.days,
delta.seconds//3600,
(delta.seconds//60)%60,
int(delta.total_seconds()%60)))
我相信它也仅适用于
date
和 time
模块。
考虑到使输出更加用户友好的要求,并假设使用 Flask 和 jinja,并假设一个名为
some_blueprint
的蓝图,我们可以在 Flask 控制器中执行自定义过滤器功能,如下所示:
@some_blueprint.app_template_filter()
def whendat(date_obj):
formaString = "Whenever"
retValMins = (datetime.today() - date_obj).total_seconds()/60
if retValMins < 0:
# Future
formatString = "{:,.0f} minutes from now".format(abs(retValMins))
else:
formatString = "{:,.0f} minutes ago".format(retValMins)
if abs(retValMins) > 120:
# Use Hours if minutes > 120
retValHours = (datetime.today() - date_obj).total_seconds()/60/60
if retValHours < 0:
# Future
formatString = "{:,.0f} hours from now".format(abs(retValHours))
else:
formatString = "{:,.0f} hours ago".format(retValHours)
if abs(retValHours) > 48:
# Use Days if hours > 48
retValDays = (datetime.today() - date_obj).days
print(retValDays)
if retValDays < 0:
# Future
formatString = "{:,.0f} days from now".format(abs(retValDays))
else:
formatString = "{:,.0f} days ago".format(retValDays)
return formatString
在你的 Jinja 模板中,像这样使用:
{{ record.SomeDtTm | whendat }}
显然,您可以选择自己何时切换单位的阈值。 您还可以修改格式字符串来添加