How to Show Local Time in Django

In this article, we show how to display local time in Django.
So we all know there are many different time zones in the world. If you are in New York, you are in a different time zone than Texas. Denver has a different time zone than California, etc.
How do we put in the correct time for a user based on their time zone?
And the way to do this is through changing the time zone based on the user's time zone.
Django saves the time by default always as UTC, which is coordinated universal time.
This you can see as a time that won't be specific to a user's local time zone, but can be used as the base to get to the user's local time.
So if you want to show the local time in the United States, there are 6 major time zones.
There's eastern time (New York), central time (chicago), mountain time (denver), pacific time (california), Hawaii–Aleutian time (Hawaii), and Alaska Daylight Time (Alaska). There are other time zones but those are the major ones used.
How can we then convert the default UTC time zone to one of these local time zones in a Django template?
The first thing we must do in the template file is enter one line at the top,
shown below.
Once you have this line in the code, you can now format date objects in django with the timezone filter.
Before we go into the actual django template code, you can change the default UTC time zone to any time zone based on the following chart shown at the link: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
The time zone for eastern time is, 'America/New_York'
The time zone for central time is, 'America/Chicago'
The time zone for mountain time is, 'America/Denver'
The time zone for pacific time is, 'America/Los_Angeles'
The time zone for Alaska Standard time is, 'America/Anchorage'
The time zone for Hawaii-Aleutian time is, 'Pacific/Honolulu'
So to show the time in Eastern Standard time is for a date object is shown below.
If you want to change it to Central Standard time, the code is shown below.
These are just the time zones for the United States and not even all of them.
You can change the time zone to any time zone in the world.
To find the local time zone of a user, there is no definitive way of doing this but by the user choosing him or herself his/her time zone.
So you want to set up some type of form in which you place a number of time zones in the form and a user can select his/her timezone and then you can save this in the database.
You can then use if statements to show the proper time zone.
This is shown in the code below.
So this is how we can display the local time of a user in Django.
Related Resources
How to Randomly Select From or Shuffle a List in Python