Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Django automatically detect the end user's timezone?

I am 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.

like image 575
Max Miller Avatar asked Dec 29 '17 19:12

Max Miller


2 Answers

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.

like image 147
xyres Avatar answered Oct 18 '22 03:10

xyres


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

like image 22
Jason Avatar answered Oct 18 '22 05:10

Jason