Ouput timezone aware django datetime fields without filters

前端 未结 2 1489
無奈伤痛
無奈伤痛 2021-01-24 14:23

Hi i upgraded to django 1.4 and i want to take advantage of the timezone support, i got a few datetime fields saved in postgres, and they were saved assuming the timezone of my

相关标签:
2条回答
  • 2021-01-24 14:52

    Actually Django Documentation states:

    Even if your Web site is available in only one time zone, it’s still good practice to store data in UTC in your database. One main reason is Daylight Saving Time (DST). Many countries have a system of DST, where clocks are moved forward in spring and backward in autumn. If you’re working in local time, you’re likely to encounter errors twice a year, when the transitions happen. (The pytz documentation discusses these issues in greater detail.) This probably doesn’t matter for your blog, but it’s a problem if you over-bill or under-bill your customers by one hour, twice a year, every year. The solution to this problem is to use UTC in the code and use local time only when interacting with end users.

    Furthermore:

    When time zone support is enabled, Django uses time-zone-aware datetime objects. If your code creates datetime objects, they should be aware too. In this mode, the example above becomes:

    import datetime
    from django.utils.timezone import utc
    
    now = datetime.datetime.utcnow().replace(tzinfo=utc)
    

    Time zone aware output in templates When you enable time zone support, Django converts aware datetime objects to the current time zone when they’re rendered in templates. This behaves very much like format localization.

    And finally, without monkey patching anything: https://docs.djangoproject.com/en/1.6/topics/i18n/timezones/#template-tags

    0 讨论(0)
  • 2021-01-24 15:02

    Unfortunately the only way I found to work with this is to convert the date to users time zone and provide a custom template tag to get the piece you want, something like:

    {% url event artist_slug=concert.slug_name hour=concert.datetime|localtime|hour_of_day %}
    

    Where hour_of_day is a custom tag returns the current hour in the correct localtime.

    0 讨论(0)
提交回复
热议问题