要在网页上使用Python Flask显示当前时间,你需要创建一个简单的Flask应用,并在其中嵌入当前时间的显示。以下是一个基础的示例,展示了如何实现这一功能:
from flask import Flask, render_template
from datetime import datetime
app = Flask(__name__)
@app.route('/')
def index():
current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
return render_template('index.html', current_time=current_time)
if __name__ == '__main__':
app.run(debug=True)
在上面的代码中,我们创建了一个Flask应用,并定义了一个路由/
,当访问这个路由时,会调用index
函数。这个函数获取当前时间,并将其传递给名为index.html
的模板文件。
接下来,你需要创建一个templates
文件夹,并在其中创建index.html
文件,内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Current Time</title>
</head>
<body>
<h1>当前时间是: {{ current_time }}</h1>
</body>
</html>
保存上述文件后,在命令行中运行Python脚本,然后打开浏览器访问http://127.0.0.1:5000/
,你应该能看到当前的时间显示在网页上。
index.html
文件位于正确的templates
文件夹内。通过以上步骤,你应该能够在网页上成功显示当前时间。如果遇到其他问题,可以检查错误信息并根据提示进行调试。
领取专属 10元无门槛券
手把手带您无忧上云