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.

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
Max Miller
  • 87
  • 3
  • 4

3 Answers3

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.

xyres
  • 20,487
  • 3
  • 56
  • 85
  • 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. – Max Miller Dec 30 '17 at 04:41
  • 2
    @MaxMiller You've to set [`USE_TZ=True`](https://docs.djangoproject.com/en/2.0/ref/settings/#std:setting-USE_TZ) to enable timezone support. – xyres Dec 30 '17 at 08:47
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

Jason
  • 11,263
  • 21
  • 87
  • 181
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.

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129