Flask框架的web页面显示当前时间和上一个时段时间

需要在python Flask框架的web页面显示当前时间和上一个时段时间。
譬如此时为 2023年7月6日22时,显示就为“2023年7月6日21时—2023年7月6日22时”

基于new bing部分指引作答:
您可以使用Python中的datetime模块来获取当前时间,并进行一些计算来获取上一个时段的时间。然后,在Flask框架的Web页面中使用模板来显示这些时间信息。

以下是一个示例代码,展示了如何在Flask框架的Web页面中显示当前时间和上一个时段的时间:

from flask import Flask, render_template
from datetime import datetime, timedelta

app = Flask(__name__)

@app.route('/')
def index():
    current_time = datetime.now()
    previous_time = current_time - timedelta(hours=1)
    
    # 格式化时间字符串
    current_time_str = current_time.strftime("%Y年%m月%d日%H时")
    previous_time_str = previous_time.strftime("%Y年%m月%d日%H时")
    
    time_range_str = f"{previous_time_str}—{current_time_str}"
    
    return render_template('index.html', time_range=time_range_str)

if __name__ == '__main__':
    app.run()

在上面的代码中,我们使用datetime.now()获取当前时间,然后使用timedelta(hours=1)来计算上一个时段的时间。然后,我们使用strftime()方法将时间对象转换为自定义的时间字符串格式。

在模板文件index.html中,您可以使用{{ time_range }}来显示时间范围。例如:

<!DOCTYPE html>
<html>
  <head>
    <title>显示时间范围</title>
  </head>
  <body>
    <h1>{{ time_range }}</h1>
  </body>
</html>

当您访问Flask应用的根路径时,它将呈现index.html模板,并将时间范围传递给模板以显示在页面上。

请注意,这只是一个简单的示例,您可以根据您的需求进行修改和扩展。

# 导入python中的日期处理包
from datetime import datetime, timedelta

# 当前时间
currentDate = datetime.now()
# 上一个时间段
prevDate = currentDate - timedelta(hours=1)
# 格式化输出
print(currentDate.strftime('%Y年%m月%d日%H时'), '-', prevDate.strftime('%Y年%m月%d日%H时'))

运行结果:

img

你的html页面是只要一个这时间段的显示吗? 效果是下面这样吗?

img


如果是的话,代码我给你贴出来,非常简单:
后端代码

from flask import Flask, render_template
from datetime import datetime, timedelta

app = Flask(__name__)

@app.route('/')
def index():
    # 获取当前时间
    current_time = datetime.now()
    
    # 计算上一个时段的时间
    previous_time = current_time - timedelta(hours=1)
    
    # 格式化时间字符串
    current_time_str = current_time.strftime("%Y年%m月%d日%H时")
    previous_time_str = previous_time.strftime("%Y年%m月%d日%H时")
    
    # 构造显示字符串
    display_str = f"{previous_time_str} - {current_time_str}"
    
    return render_template('index.html', display_str=display_str)

if __name__ == '__main__':
    app.run()

前端html页面代码:

<!DOCTYPE html>
<html>
  <head>
    <title>显示时间</title>
  </head>
  
  <body>
    <h1>{{ display_str }}</h1>
  </body>
</html>



因为使用flask框架,页面是后端返回的,所以html页面需要放到templates文件夹里面,目录截图如下:

img


其中 server.py是后端文件
index.html是前端文件

启动的时候,直接运行后端文件,然后访问指定的地址就可以了,类似于:

img


from flask import Flask, render_template
from datetime import datetime, timedelta

app = Flask(__name__)

@app.route('/')
def index():
    # 获取当前时间
    current_time = datetime.now()
    
    # 计算上一个时段的时间
    previous_time = current_time - timedelta(hours=1)
    
    # 格式化时间字符串
    current_time_str = current_time.strftime('%Y年%m月%d日%H时')
    previous_time_str = previous_time.strftime('%Y年%m月%d日%H时')

    # 构造要显示的时间范围字符串
    time_range_str = f'{previous_time_str}{current_time_str}'

    # 将时间信息传递给模板并渲染
    return render_template('index.html', time_range=time_range_str)

if __name__ == '__main__':
    app.run()

可以使用js实现实时变化效果,当然也可后端生成参数的方式


from flask import Flask, render_template
from datetime import datetime, timedelta
 
app = Flask(__name__)
 
@app.route('/')
def index():
    current_time = datetime.now()
    previous_time = current_time - timedelta(hours=1)
    
    # 格式化时间字符串
    current_time_str = current_time.strftime("%Y年%m月%d日%H时")
    previous_time_str = previous_time.strftime("%Y年%m月%d日%H时")
    
    time_range_str = f"{previous_time_str}—{current_time_str}"
    
    return render_template('index.html', time_range=time_range_str)
 
if __name__ == '__main__':
    app.run()
不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 你可以看下这个问题的回答https://ask.csdn.net/questions/7521575
  • 这篇博客也不错, 你可以看下python + Flask实现日志在web网页实时更新显示
  • 您还可以看一下 杨千锋老师的Web开发之Flask框架从入门到精通课程中的 Flask介绍-1小节, 巩固相关知识点
  • 以下回答来自chatgpt:

    首先,要在Flask中显示当前时间和上一个时段时间,可以使用Python的datetime模块来获取当前时间和上一个时段的时间。然后,在Flask框架中将这些时间传递给前端页面进行显示。

    下面是具体的解决方案:

    1. 在后端代码中,导入datetime模块,以及Flask和render_template函数:
    from datetime import datetime, timedelta
    from flask import Flask, render_template
    
    1. 创建Flask应用程序对象:
    app = Flask(__name__)
    
    1. 定义一个视图函数,用于处理请求并返回页面:
    @app.route('/')
    def display_time():
        current_time = datetime.now() # 获取当前时间
        previous_time = current_time - timedelta(hours=1) # 获取上一个时段时间
    
        # 将时间格式化为所需的字符串形式
        current_time_str = current_time.strftime("%Y年%m月%d日%H时")
        previous_time_str = previous_time.strftime("%Y年%m月%d日%H时")
    
        # 渲染模板并传递时间数据给前端页面
        return render_template('time.html', current_time=current_time_str, previous_time=previous_time_str)
    
    1. 创建一个名为time.html的模板文件,用于在页面上显示时间:
    <!DOCTYPE html>
    <html>
      <head>
        <title>显示时间</title>
      </head>
      <body>
        <h1>当前时间:{{ current_time }}</h1>
        <h1>上一个时段时间:{{ previous_time }}</h1>
      </body>
    </html>
    
    1. 启动Flask应用程序:
    if __name__ == '__main__':
        app.run()
    

    这样,当访问Flask应用程序的根路径时,就会显示当前时间和上一个时段时间。

    请注意,以上代码是基于Flask框架的简单示例代码,你可能需要根据自己的实际需求进行修改和调整。另外,为了在页面上显示时间,你可能还需要使用前端的样式和JavaScript来进行美化和动态更新。这部分内容可以根据具体情况自行扩展。


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^

要在Python Flask框架的web页面上显示当前时间和上一个时段时间,可以使用datetime模块来获取当前时间并进行处理。以下是一个示例代码:

from flask import Flask, render_template
from datetime import datetime, timedelta

app = Flask(__name__)

@app.route('/')
def index():
    current_time = datetime.now()
    previous_time = current_time - timedelta(hours=1)

    time_range = f"{previous_time.strftime('%Y年%m月%d日%H时')}{current_time.strftime('%Y年%m月%d日%H时')}"

    return render_template('index.html', time_range=time_range)

if __name__ == '__main__':
    app.run()

在上面的示例中,我们使用datetime.now()获取当前时间,并使用timedelta(hours=1)获取上一个时段的时间。然后,使用strftime方法将时间对象转换为指定的日期和时间格式。最后,将时间范围传递给模板(例如index.html)进行显示。

index.html模板中,您可以使用{{ time_range }}来显示时间范围,例如:

<!DOCTYPE html>
<html>
<head>
    <title>时间范围</title>
</head>
<body>
    <h1>当前时间和上一个时段时间</h1>
    <p>{{ time_range }}</p>
</body>
</html>

运行Flask应用后,访问首页即可在web页面上显示当前时间和上一个时段时间。请注意,您可能需要根据实际情况进行适当的调整和美化。

有用望采纳:
以下是使用Python Flask框架在web页面上显示当前时间和前一个时段时间的示例代码:

from flask import Flask, render_template
from datetime import datetime, timedelta

app = Flask(__name__)

@app.route('/')
def show_time():
    now = datetime.now()  # 获取当前时间
    prev_time = now - timedelta(hours=1)  # 计算前一个时段时间

    # 格式化时间字符串
    current_time_str = now.strftime("%Y年%m月%d日%H时")
    prev_time_str = prev_time.strftime("%Y年%m月%d日%H时")

    # 生成要显示在页面上的文本
    display_text = f"{prev_time_str}—{current_time_str}"

    return render_template('index.html', display_text=display_text)

if __name__ == '__main__':
    app.run()

在代码中,我们使用了datetime模块来获取当前时间,并通过减去timedelta来计算前一个时段的时间。然后,使用strftime()方法来将时间格式化为指定的字符串格式,并将生成的文本传递给模板。

在Flask应用程序的根目录下,我们需要创建一个名为templates的文件夹,并在其中创建一个名为index.html的模板文件。在模板文件中,我们可以使用{{ display_text }}来显示传递的文本。

示例中的代码可以在Flask应用程序启动后访问"http://localhost:5000/"来显示当前时间和前一个时段时间。你可以根据需要自定义样式和布局来美化该页面。

上结果,按照目录放即可

img

代码
py文件

# 导入Flask和datetime模块
from flask import Flask, render_template
import datetime

# 创建Flask应用对象
app = Flask(__name__)

# 定义路由和视图函数
@app.route("/")
def index():
    # 获取当前时间
    now = datetime.datetime.now()
    # 获取上一个时段时间
    prev = now - datetime.timedelta(hours=1)
    # 格式化时间为字符串
    now_str = now.strftime("%Y年%m月%d日%H时")
    prev_str = prev.strftime("%Y年%m月%d日%H时")
    # 拼接字符串
    time_str = prev_str + "—" + now_str
    # 渲染到web页面上
    return render_template("index.html", time=time_str)

# 运行Flask应用
if __name__ == "__main__":
    app.run()


html文件

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>时间显示</title>
</head>
<body>
    <h1>当前时间和上一个时段时间</h1>
    <p>{{ time }}</p>
</body>
</html>


datetime模块


from datetime import datetime, timedelta

@app.route('/')
def index():
    current_time = datetime.now()
    previous_time = current_time - timedelta(minutes=1)
    time_str = f"{current_time.strftime('%Y-%m-%d %H:%M')}—{previous_time.strftime('%Y-%m-%d %H:%M')}"
    return f"当前时间为 {time_str}"

在后台的代码中生成时间,然后将数据返回到前台页面显示就可以啦,其中,后面生成时间的方法如下:

 current_time = datetime.datetime.now()  
    previous_hour = current_time - datetime.timedelta(hours=1)  
    return render_template('index.html', current_time=current_time, previous_hour=previous_hour)


py Flask框架的web页面显示当前时间和上一个时段时间


from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
 
app = Flask(__name__)
 
# Set a secret key for the form. This is used to protect the form from
# Cross-Site Request Forgery (CSRF) attacks.
app.config['SECRET_KEY'] = 'your-secret-key'
 
class LoginForm(FlaskForm):
    username = StringField('Username')
    password = PasswordField('Password')
    submit = SubmitField('Log In')
 
class RegisterForm(FlaskForm):
    username = StringField('Username')
    password = PasswordField('Password')
    submit = SubmitField('Sign Up')
 
@app.route('/login')
def login():
    form = LoginForm()
    return render_template('login.html', form=form)
 
@app.route('/register')
def register():
    form = RegisterForm()
    return render_template('register.html', form=form)
 
if __name__ == '__main__':
    app.run()

首先,您可以使用Flask-Moment扩展来处理时间显示的问题。按照以下步骤操作:
1,安装Flask-Moment扩展。

pip install Flask-Moment

2,在您的Flask应用程序中导入所需的模块并初始化Flask-Moment。

from flask import Flask
from flask_moment import Moment

app = Flask(__name__)
moment = Moment()
moment.init_app(app)

3,在您的HTML模板中引入Flask-Moment的JS文件,并进行本地化设置(如果需要)。


<!-- 引入Flask-Moment的JS文件 -->
<script src="{{ moment.include_jquery() }}"></script>
<script src="{{ moment.include_moment() }}"></script>

<!-- 设置本地化 -->
<script>
    moment.locale('zh-cn');
</script>

4,在页面上显示时间。

<!-- 显示当前时间 -->
<p>当前时间: {{ moment().format('LLLL') }}</p>

<!-- 显示上一个时段的时间 -->
<p>上一个时段时间: {{ moment().subtract(1, 'hours').format('LLLL') }} - {{ moment().format('LLLL') }}</p>

请注意,为了在Flask中使用Flask-Moment,您需要安装和配置相关的依赖项。另外,您可能需要根据您的具体需求进行调整和自定义。

希望这可以帮助到您!
可以参考: https://zhuanlan.zhihu.com/p/64438998