Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask, get local time

Tags:

python

flask

I'm building a Flask app in Python and I would like to save the user local time.

I thought of using this

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

But this is giving me the server local time.

like image 206
Brian Avatar asked Sep 02 '25 15:09

Brian


1 Answers

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

Your purpose can be achieved by using javascript to get client side time and passing it to server.

Folder structure

.
├── 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>

Example result on console

# 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 -
like image 54
Kir Chou Avatar answered Sep 04 '25 05:09

Kir Chou