python - Flask,获取本地时间

标签 python flask

我正在用 Python 构建一个 Flask 应用程序,我想保存用户本地时间。

我想到了用这个

time.strftime('%A %B, %d %Y %H:%M:%S')

但这是给我服务器本地时间。

最佳答案

For a web application, flask is responsible for server side only.

您的目的可以通过使用 javascript 获取客户端时间并将其传递给服务器来实现。

文件夹结构

.
├── app.py
└── templates
    └── index.html

app.py

from flask import Flask, request, render_template
import time

app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/getTime", methods=['GET'])
def getTime():
    print("browser time: ", request.args.get("time"))
    print("server time : ", time.strftime('%A %B, %d %Y %H:%M:%S'));
    return "Done"

templates/index.html

<script> 
function sendTimeToServer(){
    var time = new Date();
    var i = document.createElement("img");
    i.src = "/getTime?time=" + time;
    document.getElementById("time").innerHTML = time;
}
</script>
<button onclick="sendTimeToServer()">update time</button>
<div id="time">Time: </div>

控制台上的示例结果

# 1. open browser: http://127.0.0.1:5000
# 2. click "update time" button

 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [01/Nov/2016 19:58:36] "GET / HTTP/1.1" 200 -
browser time:  Tue Nov 01 2016 19:58:37 GMT 0800 (CST)
server time:   Tuesday November, 01 2016 19:58:37
127.0.0.1 - - [01/Nov/2016 19:58:37] "GET /getTime?time=Tue%20Nov%2001%202016%2019:58:37%20GMT+0800%20(CST) HTTP/1.1" 200 -

关于python - Flask,获取本地时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40358675/

相关文章:

python - 如何使用twistd日志系统来记录我的数据?

python - 无法将 Pandas 数据框保存到csv

postgresql - 如何在 flask-sqlalchemy 中使用 INET 的 ARRAY?

python - 在 PythonAnywhere 上运行 Flask-SocketIO 应用程序会引发 IOError

python - Flask - 使用相同的 View 呈现搜索表单然后搜索结果

python - 如何使用 Flask 处理从 jquery 数据表发送的服务器端参数?

python - Groupby 对象按组的百分比变化

Python:使用日期时间格式进行 numpy 重新排列的 SpatiaLite 表?

python - 缩进错误 : unexpected unindent can't find the issue

flask - 使用flask-socketio频繁中断套接字连接