首页 > 解决方案 > 使用 Python Flask 在网页上显示时间

问题描述

我有一个任务是用烧瓶构建一个简单的网页。我已经让它工作了,并且到目前为止我的模板中都有我需要的一切。我不知道如何在我的页面上显示日期时间。我是将日期时间单独放在模板中,还是将其放在基本的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')

标签: pythonhtmlflask

解决方案


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

from datetime import datetime

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

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

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


推荐阅读