You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Flask实现服务器端运行时长计时器?

实现服务器运行时长显示功能的解决方案

问题说明

需实现功能:展示服务器启动至今的时长(小时、分钟、秒),当前在Replit部署Flask服务,但现有代码无法满足需求。

现有问题代码

from flask import Flask, render_template
from threading import Thread
import random,os,time,datetime

app = Flask(__name__)

@app.route('/')
def main():
  d = datetime.datetime.utcnow()
  jstime = int(time.mktime(d.timetuple())) * 1000 # this obviously doesn't work
    return render_template('index.html', owner=os.environ['REPL_OWNER'], name=os.environ['REPL_SLUG'], timeStart=jstime)

def run():
    app.run(host="0.0.0.0", port=random.randint(1000, 9999))
    
def keep_alive():
    server = Thread(target=run)
    server.start()

解决方案

1. 修改Flask后端代码

核心是在服务器启动时记录启动时间戳,而非每次请求都传当前时间。修改后代码:

from flask import Flask, render_template
from threading import Thread
import random, os, datetime

app = Flask(__name__)
# 服务器启动时记录UTC时间戳(毫秒),仅初始化一次
start_time = int(datetime.datetime.utcnow().timestamp() * 1000)

@app.route('/')
def main():
    return render_template(
        'index.html',
        owner=os.environ['REPL_OWNER'],
        name=os.environ['REPL_SLUG'],
        timeStart=start_time
    )

def run():
    app.run(host="0.0.0.0", port=random.randint(1000, 9999))
    
def keep_alive():
    server = Thread(target=run)
    server.start()

2. 前端index.html实时计算时长

通过前端JS实时计算当前时间与启动时间的差值,转换为时分秒并每秒更新:

<!DOCTYPE html>
<html>
<head>
    <title>服务器运行时长</title>
    <script>
        const startTimestamp = {{ timeStart }};
        
        function updateUptime() {
            const now = Date.now();
            const diffMs = now - startTimestamp;
            // 计算时分秒
            const hours = Math.floor(diffMs / (1000 * 60 * 60));
            const minutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((diffMs % (1000 * 60)) / 1000);
            
            // 补零格式化显示
            document.getElementById('uptime').textContent = 
                `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
        }
        
        // 页面加载后立即更新,之后每秒刷新一次
        window.onload = () => {
            updateUptime();
            setInterval(updateUptime, 1000);
        }
    </script>
</head>
<body>
    <h1>服务器 {{ name }} 运行时长</h1>
    <p>拥有者:{{ owner }}</p>
    <p>当前时长:<span id="uptime">00:00:00</span></p>
</body>
</html>

关键要点

  • 后端start_time在服务启动时赋值,确保是准确的启动时间点
  • 前端用Date.now()获取当前时间戳,计算差值后转换为时分秒
  • 采用UTC时间戳避免时区偏差,保证计算准确性

内容的提问来源于stack exchange,提问作者benz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 17:45:31