【发布时间】:2018-05-16 18:22:21
【问题描述】:
我正在尝试在烧瓶应用程序中将 UTC 时间转换为适当的本地时间。我想知道我是否可以检测用户的时区并动态设置它。
到目前为止,这是我的代码,仅适用于 US/Pacific 时区的所有人(datetimefilter 从 this SO question 提取)
from flask import Flask, render_template_string
import datetime
import pytz
app = Flask(__name__)
@app.template_filter('datetimefilter')
def datetimefilter(value, format='%b %d %I:%M %p'):
tz = pytz.timezone('US/Pacific') # timezone you want to convert to from UTC (America/Los_Angeles)
utc = pytz.timezone('UTC')
value = utc.localize(value, is_dst=None).astimezone(pytz.utc)
local_dt = value.astimezone(tz)
return local_dt.strftime(format)
@app.route('/')
def index():
dt = datetime.datetime.utcnow()
return render_template_string(
'''
<h4>UTC --> Local Time</h4>
Datetime right now is:
<p>{{ dt | datetimefilter }} (utc --> local)</p>
''',
dt=dt, now=now)
if __name__ == '__main__':
app.run(debug=True)
我想这无法在服务器端处理,因为时区将始终设置为服务器所在的任何位置?有没有办法通过更改datetimefilter来处理这个问题?
【问题讨论】:
标签: python datetime timezone utc pytz