简体   繁体   中英

timezone aware datetime objects in django templates

I'm having trouble understanding how to use datetime objects in a django db.

I'm storing datetime.now() in a DateTimeField but having trouble displaying it in a readable way. Currently it displays UTC time.

Should I storing a timezone with the datetimefield or should I always be converting it to my timezone during queries and template views?

This is so complicated I must be doing this completely wrong.

How would I display Pacific timezone time in a template if that were the case?

Thank you.

<tbody>
  {% for session in session_list %}
      <tr></tr><td>{{session.date}}</td><td>{{session.email}}</td><td>{{session.userData}}</td></tr>
  {% endfor %}

</tbody>

*) You can enable or disable conversion of aware datetime objects using templates tags:

{% load tz %}

{% localtime on %}
    {{ value }}
{% endlocaltime %}

{% localtime off %}
    {{ value }}
{% endlocaltime %}

*) In setting.py , you can configure TIME_ZONE and USE_TZ

Store datetime in UTC time is good(below quote from Django website):

it's still good practice to store data in UTC in your database. The 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.

Read more from the official Django Site

Just adding an answer as a reference using Django 3.x new syntax:

In template, include tz:

{% load tz %}

When displaying your timezone aware object, either use timezone:'TIMEZONE' filter or localtime filter:

Your code should look like this


<tbody>
  {% for session in session_list %}
      <tr></tr><td>{{session.date|localtime}}</td><td>{{session.email}}</td><td>{{session.userData}}</td></tr>
  {% endfor %}

</tbody>

Read more here on Django official website.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM