我正在尝试将协调世界时(UTC)时间转换为适当的本地时间在flask应用程序中。 我想知道是否可以检测用户的时区并动态设置它。这是目前为止仅适用于
US / Pacific
时区的代码(datetimefilter
来自这个SO问题)。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
来解决这个问题?