如何在页面加载时将jinja代码中的时间值转换为浏览器的本地时区?

Grr*_*rr4 5 javascript python jinja2 flask momentjs

我有一个烧瓶生成的时间值列表,格式为:YYYY-DD-MM hh:mm:ss.这些时间值作为url链接使用,并使用jinja2显示在我的html文件中,如下所示:

{% for job in jobs %}
    <a href=”{{ url_for(‘jobs/by_id’,job_id=job.job_id) }}">
    {{ job.finishtime }}              #this is the time value
    </a>
{% endfor %}

我希望这些时间值自动转换为浏览器的本地时区.我尝试使用flask-moment扩展但在完成所有说明和使用后{{ moment(job.finishtime).format('MMMM Do YYYY, h:mm:ss a') }},加载时html页面的时间不响.我也尝试过其他时刻的功能,但不断出错.

有没有更好的方法让moment.js与我的jinja代码交谈?

我希望不必处理python datetime.

Oll*_*F-G 2

不幸的是,Jinja2 是在服务器上呈现的,因此它的代码永远不会在客户端的计算机上运行 - 它无法(轻松)获取时区。
\n这意味着 Javascript在 Jinja2 模板渲染运行,因此您不能在 jinja2 标签内使用 JS。

\n\n

有几种方法可以解决这个问题/解决您的问题:

\n\n

1) 当用户第一次访问您的网站(或登录,如果可能的话)时,让一些 javascript 设置 cookie timezone。然后可以在服务器端读取它,并将其传递到模板中 - 如下所示:

\n\n
# On the server\ndef view_jobs_page(request, response):\n    import datetime\n    tz = datetime.timedelta(seconds = int(request.cookies["timezone"])) # Pass this into the Jinja2 render function\n    # ... Do stuff\n\n\n# In your template\nlocal time: {{ job.finishtime + tz }}\n
Run Code Online (Sandbox Code Playgroud)\n\n

如果不知道您正在使用的确切堆栈和代码结构,则很难给出更详细的示例。这也有使用的缺点datetime,这是您不想要的。

\n\n

2)使用javascript来应用timedelta:

\n\n
<!-- In the head -->\n<script>\n// When the page loads - the Jinja template is already rendered now\nwindow.onload = function() {\n  // Get all the elements with the given class, and map through them\n  document.querySelectorAll(".datetime_to_be_adjusted").forEach(function(el){\n    var utcTime = moment.utc(el.innerText);  // This is the time in UTC\n    utcTime.local();  // Switch to using the browser\'s local timezone\n    el.innerText = utcTime.format(\'MMMM Do YYYY, h:mm:ss a\');  // Write the local time back to the element\n  });\n}\n</script>\n...\n{% for job in jobs %}\n    <a href=\xe2\x80\x9d{{ url_for(\xe2\x80\x98jobs/by_id\xe2\x80\x99,job_id=job.job_id) }}" class="datetime_to_be_adjusted">\n        {{ job.finishtime }}\n    </a>\n{% endfor %}\n
Run Code Online (Sandbox Code Playgroud)\n\n

这当然依赖于页面中包含的 momentJS,并使用它的UTC 解析机制

\n