Does Django automatically detect the end user's timezone?
Asked Answered
R

3

7

I'm building an application in Django which allows the end-user to retrieve information which is sensitive to the time of day (12 am to 12 am) on a given day. I store this information in my database as an integer representing the seconds since midnight in 30-minute increments. I was looking at Django's timezone documentation: https://docs.djangoproject.com/en/2.0/topics/i18n/timezones/ and found myself confused on whether or Django automatically uses the end-users time, or if I must collect this information and account for it in my views.

Any information would be helpful! Thanks.

Rouault answered 29/12, 2017 at 19:33 Comment(0)
N
19

Django doesn't detect end user's timezone. It saves the objects in the database in UTC time.

Then you can convert the UTC time to the client's time on the browser using JavaScript for displaying.

Django also provides methods to convert timezones on the server for a particular request or a session: See docs. However, using JavaScript is definitely the easier option.

Django also has a TIME_ZONE setting. But this is very limited. Django uses this timezone for displaying the time in admin or other places. It's very limited because only one timezone is supported, and it won't change depending upon the client's timezone.


Converting UTC to localtime on a user's browser using JavaScript is the best and easiest solution.


Note: The older version of this answer (which was marked accepted) can be found here.

Nifty answered 29/12, 2017 at 20:32 Comment(2)
Huh, I wasn't aware of this. For a few sections of the project I am using the Javascript method and it's working out well. For the part I am working on, the user needs to see something from, say, 10 AM to 2 PM and only on those times, repeated every other day. I think with what you said Django should understand this natively. If not, I will send the local UTC time with my requests and serve the information back to the user based on that.Rouault
@MaxMiller You've to set USE_TZ=True to enable timezone support.Nifty
O
4

No. There are some packages where you can detect timezone based on IP address. You can look at https://github.com/adamcharnock/django-tz-detect

Osprey answered 29/12, 2017 at 19:36 Comment(0)
W
0

No, Django doesn't automatically detect and apply the user's current time zone even if USE_TZ = True and TIME_ZONE = 'UTC' or TIME_ZONE = 'America/New_York'.

But, there is django-tz-detect which can automatically detect and apply the user's current timezone rather than applying only one timezone set to TIME_ZONE in settings.py. You can see my answer explaining how to set django-tz-detect in detail.

Wormeaten answered 30/6, 2023 at 17:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.