archae0pteryx archae0pteryx - 1 year ago 240
Javascript Question

Working with time in Python + Flask

Best way to display UTC in realtime with Flask?

I've got a little app that I would like to display UTC down to the ms. I have tried hacking together something with flask-moment (moment.js) but the refresh interval is only per/min. Here's what I've got:

import os
import json
import requests

from functools import wraps
from flask import Flask, request, jsonify, session, redirect, render_template, send_from_directory

from flask_bower import Bower
from flask_moment import Moment
app = Flask(__name__)
app.debug = True

app.secret_key = "supersecretkey"

moment = Moment(app)

def index():
return render_template('/index.html')

if __name__ == "__main__":


<!DOCTYPE html>
<html lang=en>
<meta charset=utf-8>
{{ moment.include_jquery() }}
{{ moment.include_moment() }}
<h1>{{ moment().format('xxx') }}</h1>

My question is exacly: What is the proper way to render this clock with milliseconds? That is always running?

Answer Source

This JS snippet should refresh the unix timestamp (down to milliseconds) to an html element with id="timestamp"; e.g., <h1 id="timestamp"></h1>, every 100ms.

var update = function () {
   // using jQuery (really not a must):
   // or without jquery
   document.getElementById("timestamp").innerHTML = moment().format('x');

    setInterval(update, 100);

If you already use jQuery, the first line in the update function should work, for strict JS, use the lower. As @albert suggested, use the right tool for the job, this is a strictly frontend update, on the client side.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download