0

The time that is being inserted in database is default UTC, not the timezone based time..I do not understand why is this happening, even though I am particularly specifying, in the query, the time that I want to be inserted.

In my Model I have

class leave(models.Model): 
    date_created = models.DateTimeField(auto_now_add=True)

In my settings I have

TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

In my views i am setting timezone based on employee country

if employees.objects.get(emp_id=request.user.username).emp_loc == 'IND':
   tzone=pytz.timezone('Asia/Calcutta')
elif employees.objects.get(emp_id=request.user.username).emp_loc == 'MLA':
   tzone=pytz.timezone('Asia/Manila')
elif employees.objects.get(emp_id=request.user.username).emp_loc == 'MPLS':
   tzone=pytz.timezone('CST6CDT')

And then I am creating leave and updating timezone based on country

new_leave = leave.objects.create(employee=employees.objects.get(emp_id = userid.emp_id), start_date=sdt, end_date=edt, ltype=ltyp, message=des,date_created=datetime.now(tzone))
new_leave.save()

Thanks in Advance.

divya
  • 315
  • 1
  • 5
  • 15
  • I answered this, but then realized that the question and my answer duplicated this one: [Django DateTimeField Stores datetime regardless of the tzinfo](https://stackoverflow.com/questions/33280135/django-datetimefield-stores-datetime-regardless-of-the-tzinfo) – Kevin Christopher Henry Nov 08 '17 at 13:41

1 Answers1

0

You can create a middleware that handles the conversion of date and time, import pytz

from django.utils import timezone
from django.utils.deprecation import MiddlewareMixin

class TimezoneMiddleware(MiddlewareMixin):
    def process_request(self, request):
        tzname = request.session.get('django_timezone')
        if tzname:
            timezone.activate(pytz.timezone(tzname))
        else:
            timezone.deactivate()

and then you can as easily create the view with the conditions that you indicated earlier. Best if you read the documentation as Kevin suggested.

Samuel Omole
  • 185
  • 1
  • 7