Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python-Django timezone is not working properly

I am working on Django based website. I am trying to get correct timezone and time to be displayed. But it is not working properly. I live in Dallas, Texas. So my default timezone is 'America/Chicago'.

My settings.py file has these lines of code.

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

I have datetime, and pytz installed. So when I am trying to save time in database, my codes are,

from datetime import datetime
import pytz

utc = pytz.utc

database = Database.objects.get(id=1)

databas.time = utc.localize(datetime.now())

database.save()

so when I check into database, updated time is 2015-10-20 23:13:04

instead of 2015-10-20 18:13:04

and when I print it out in template by codes below, I get this output Oct. 20, 2015, 1:13 p.m.

{{ database.time|localtime }}

I am confused how to use datetime, pytz and all to get accurate time along with settings.py file.

What I want to do is I want to save UTC time. But when I print out I want to get visitor's timezone and print time according to user. My website will be accessible only in United States for now. My model has

time = models.DateTimeField(auto_now_add=True)

and it is saving some different time. I have another model where I have column named expire time where I am using following codes to save,

expire_time = utc.localize(datetime.now()+ timedelta(hours=24))

means I want to expire a link after 24 hours. But this timezone is confusing me. Can anyone help me? I don't know what should I use in my codes to get proper timezone.

like image 577
Django Learner Avatar asked Oct 21 '15 00:10

Django Learner


1 Answers

If you set USE_TZ = True Django stores datetimes in UTC. Use the following to create a timezone aware datetime.now:

from django.utils import timezone
from datetime import timedelta

database.time = timezone.now()
expire_time = timezone.now() + timedelta(hours=24)

You can then use activate() to set the current time zone to the end user’s actual time zone. Have a look at "Selecting the current time zone" to see an example how a user can select his timezone and how this selection is used to activate his timezone.

like image 168
Reto Aebersold Avatar answered Sep 22 '22 19:09

Reto Aebersold