[python] How to set the timezone in Django?

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, so I changed it to

TIME_ZONE = 'UTC+2'

It gives the error ValueError: Incorrect timezone setting: UTC+2. What is the correct way of doing this?

Thanks!

This question is related to python python-3.x django timezone utc

The answer is


  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:

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

or use the template filters concisely:

                <td> 
                    {% load tz %}
                    {{ message.log_date | localtime | time:'H:i:s' }}
                </td>
  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.


Universal solution, based on Django's TZ name support:

UTC-2 = 'Etc/GMT+2'
UTC-1 = 'Etc/GMT+1'
UTC = 'Etc/GMT+0'
UTC+1 = 'Etc/GMT-1'
UTC+2 = 'Etc/GMT-2'

+/- is intentionally switched.


To get a set of all valid timezone names (ids) from the tz database, you could use pytz module in Python:

>>> import pytz # $ pip install pytz
>>> pytz.all_timezones_set
LazySet({'Africa/Abidjan',
         'Africa/Accra',
         'Africa/Addis_Ababa',
         'Africa/Algiers',
         'Africa/Asmara',
         'Africa/Asmera',
         ...
         'UTC',
         'Universal',
         'W-SU',
         'WET',
         'Zulu'})

Valid timeZone values are based on the tz (timezone) database used by Linux and other Unix systems. The values are strings (xsd:string) in the form “Area/Location,” in which:

Area is a continent or ocean name. Area currently includes:

  • Africa
  • America (both North America and South America)
  • Antarctica
  • Arctic
  • Asia
  • Atlantic
  • Australia
  • Europe
  • Etc (administrative zone. For example, “Etc/UTC” represents Coordinated Universal Time.)
  • Indian
  • Pacific

Location is the city, island, or other regional name.

The zone names and output abbreviations adhere to POSIX (portable operating system interface) UNIX conventions, which uses positive (+) signs west of Greenwich and negative (-) signs east of Greenwich, which is the opposite of what is generally expected. For example, “Etc/GMT+4” corresponds to 4 hours behind UTC (that is, west of Greenwich) rather than 4 hours ahead of UTC (Coordinated Universal Time) (east of Greenwich).

Here is a list all valid timezones

You can change time zone in your settings.py as follows

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Kolkata'

USE_I18N = True

USE_L10N = True

USE_TZ = True

Use Area/Location format properly. Example:

TIME_ZONE = 'Asia/Kolkata'

I found this question looking to change the timezone in my Django project's settings.py file to the United Kingdom.

Using the tz database in jfs' solution I found the answer:

    TIME_ZONE = 'Europe/London'

  1. download latest pytz file (pytz-2019.3.tar.gz) from:

    https://pypi.org/simple/pytz/
    
  2. copy and extract it to site_packages directory on yor project

  3. in cmd go to the extracted folder and run:

    python setup.py install
    
  4. TIME_ZONE = 'Etc/GMT+2' or country name


Choose a valid timezone from the tzinfo database. They tend to take the form e.g. Africa/Gaborne and US/Eastern

Find the one which matches the city nearest you, or the one which has your timezone, then set your value of TIME_ZONE to match.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to python-3.x

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation Replace specific text with a redacted version using Python Upgrade to python 3.8 using conda "Permission Denied" trying to run Python on Windows 10 Python: 'ModuleNotFoundError' when trying to import module from imported package What is the meaning of "Failed building wheel for X" in pip install? How to downgrade python from 3.7 to 3.6 I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? Iterating over arrays in Python 3 How to upgrade Python version to 3.7?

Examples related to django

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip Pylint "unresolved import" error in Visual Studio Code Is it better to use path() or url() in urls.py for django 2.0? Unable to import path from django.urls Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?' ImportError: Couldn't import Django Django - Reverse for '' not found. '' is not a valid view function or pattern name Class has no objects member Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries How to switch Python versions in Terminal?

Examples related to timezone

How to set the timezone in Django? How to convert Moment.js date to users local timezone? What does this format means T00:00:00.000Z? How do I get the current timezone name in Postgres 9.3? MySQL JDBC Driver 5.1.33 - Time Zone Issue Python get current time in right timezone Symfony2 and date_default_timezone_get() - It is not safe to rely on the system's timezone settings PHP date() with timezone? How to store a datetime in MySQL with timezone info Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST

Examples related to utc

Convert LocalDateTime to LocalDateTime in UTC How to set the timezone in Django? Java Convert GMT/UTC to Local time doesn't work as expected Should MySQL have its timezone set to UTC? How to Convert UTC Date To Local time Zone in MySql Select Query How to convert UTC timestamp to device local time in android Convert python datetime to epoch with strftime Convert Java Date to UTC String How do I get a UTC Timestamp in JavaScript? Converting datetime.date to UTC timestamp in Python