【问题标题】:How to change timezone in http response (django server)?如何更改 http 响应(django 服务器)中的时区?
【发布时间】:2017-04-07 09:46:29
【问题描述】:

我正在运行没有任何代理的 django 服务器:

python manage.py runserver 0.0.0.0:80

我在linux服务器上设置了我的本地时区,这是正确的:

root@83b3bf90b5c5:/app# date
Fri Apr  7 12:38:42 MSK 2017

我还在 django 项目的 settings.py 上设置了本地时区:

TIME_ZONE = 'Europe/Moscow'

并检查了它:

>>> from django.utils.timezone import localtime, now
>>> localtime(now())
datetime.datetime(2017, 4, 7, 12, 38, 42, 196476, 
tzinfo=<DstTzInfo 'Europe/Moscow' MSK+3:00:00 STD>)

但是当我从客户端(Google Chrome 浏览器)打开任何网页时 - 在 http 响应标头中,时区不是本地的:

Date:Fri, 07 Apr 2017 09:38:42 GMT

如何更改全球所有项目的 http 标头中的时区?

【问题讨论】:

    标签: python django http datetime timezone


    【解决方案1】:

    如何更改全球所有项目的 http 标头中的时区?

    HTTP 日期标头是 defined,因为它是 UTC(由于历史原因,由字符 GMT 表示),因此 Django 或任何其他服务器或框架都不允许您将它们本地化到您的时区。你有这样做的理由吗?

    Django 确实有切换到本地时区的方法(请参阅activate()),但这仅适用于特定于应用程序的内容,而不适用于 HTTP 标头。

    【讨论】:

    • 谢谢,没有理由对它们进行本地化。我只是想找出他们为什么在UTC。您的回答和 IETF 参考有所帮助。
    【解决方案2】:

    使用pytz,作为astimezone方法

    from pytz import timezone
    
    time_zone = timezone(settings.TIME_ZONE)
    currentTime = currentTime.astimezone(time_zone)
    

    在您的中间件中:

    import pytz
    
    from django.utils import timezone
    from django.utils.deprecation import MiddlewareMixin
    
    class TimezoneMiddleware(MiddlewareMixin):
        def process_request(self, request):
            tzname = request.session.get('django_timezone')
            if tzname:
                timezone.activate(pytz.timezone(tzname))
            else:
                timezone.deactivate()
    

    在你看来.py

    from django.shortcuts import redirect, render
    
    def set_timezone(request):
        if request.method == 'POST':
            request.session['django_timezone'] = request.POST['timezone']
            return redirect('/')
        else:
            return render(request, 'template.html', {'timezones': pytz.common_timezones})
    

    在你的 Templete.html 中

    {% load tz %}
    {% get_current_timezone as TIME_ZONE %}
    <form action="{% url 'set_timezone' %}" method="POST">
        {% csrf_token %}
        <label for="timezone">Time zone:</label>
        <select name="timezone">
            {% for tz in timezones %}
            <option value="{{ tz }}"{% if tz == TIME_ZONE %} selected="selected"{% endif %}>{{ tz }}</option>
            {% endfor %}
        </select>
        <input type="submit" value="Set" />
    </form>
    

    【讨论】:

    猜你喜欢
    • 2020-04-22
    • 2011-08-26
    • 1970-01-01
    • 2013-08-20
    • 2012-04-24
    • 2014-04-29
    • 2015-04-30
    • 2021-12-12
    • 1970-01-01
    相关资源
    最近更新 更多