How to set the timezone in Django?

后端 未结 8 891
萌比男神i
萌比男神i 2020-11-29 19:33

In my django project\'s settings.py file, I have this line :

TIME_ZONE = \'UTC\'

But I want my app to run in UTC+2 timezone, s

8条回答
  •  清酒与你
    2020-11-29 20:08

    1. Change the TIME_ZONE to your local time zone, and keep USE_TZ as True in 'setting.py':

      TIME_ZONE = 'Asia/Shanghai'

      USE_I18N = True

      USE_L10N = True

      USE_TZ = True

    2. This will write and store the datetime object as UTC to the backend database.

    3. Then use template tag to convert the UTC time in your frontend template as such:

                   
                      {% load tz %}
                      {% get_current_timezone as tz %}
                      {% timezone tz %}
                          {{ message.log_date | time:'H:i:s' }}
                      {% endtimezone %} 
                  
      

    or use the template filters concisely:

                     
                        {% load tz %}
                        {{ message.log_date | localtime | time:'H:i:s' }}
                    
    
    1. You could check more details in the official doc: Default time zone and current time zone

      When support for time zones is enabled, Django stores datetime information in UTC in the database, uses time-zone-aware datetime objects internally, and translates them to the end user’s time zone in templates and forms.

提交回复
热议问题