【问题标题】:Display time on webpage with Python Flask使用 Python Flask 在网页上显示时间
【发布时间】:2021-03-14 00:38:23
【问题描述】:

我有一个任务是用烧瓶构建一个简单的网页。我已经让它工作了,并且到目前为止我的模板中都有我需要的一切。我不知道如何在我的页面上显示日期时间。我是将日期时间单独放在模板中,还是将其放在基本的python代码中?我的说明说只使用标准的 python 日期时间函数。但是当我测试我的页面时它没有显示。

from flask import Flask
from flask import render_template
import datetime

app = Flask(__name__)

@app.route('/')
def index():
    return show_home()


def show_home():
    return render_template('index.html')

@app.route('/ingredients/')
def ingredients():
    return show_ingredients()

def show_ingredients():
    return render_template('ingredients.html')

@app.route('/cooking_instructions/')
def cook_it():
    return show_cook_it()

def show_cook_it():
    return render_template('cooking_instructions.html')

【问题讨论】:

  • 我什至没有看到您在程序中的任何地方使用 datetime 模块。您需要使用datetime.now() 并将其显示在您的模板之一中。

标签: python html flask


【解决方案1】:

您可以像这样将日期时间的字符串表示形式传递给render_template 函数:

from datetime import datetime

@app.route('/example')
def example():
    return render_template('template.html', datetime = str(datetime.now()))

然后您可以使用语法{{ datetime }} 访问模板中的变量。当然,您可以通过在 datetime 对象上使用 strftime 方法来自定义您的 datetime 在模板中的外观。

这不会是动态的,因此一旦模板呈现日期时间将不会更新。如果您正在寻找计数时钟,则需要用 javascript 编写该代码。看看这个例子HTML Display Current date

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多