Date time and Date format localization with Django Rest Framework - django

I am creating API with DRF and Django 1.8 using python 2.7.x and Postgres 9.4. API is consumed by front end using AngularJS. I need to do time conversion to different time zones as per user set timezone. I tried creating a middleware as shown below -
import pytz
from django.utils import timezone
from django.conf import settings
class TimezoneMiddleware(object):
def process_request(self, request):
request.session["user_pref_timezone"] = "Europe/Paris"
tzname = request.session.get('user_pref_timezone')
settings.DATE_FORMAT = request.session.get('date')
settings.TIME_FORMAT = request.session.get('time')
if tzname:
timezone.activate(pytz.timezone(tzname))
else:
timezone.deactivate()
And added it to settings.py under MIDDLEWARE_CLASSES as
'core.middleware.timezone.TimezoneMiddleware',
in settings.py I have added ,
USE_TZ = True
import pytz
TIMEZONES = ( (tz, tz) for tz in pytz.common_timezones )
still I can not see my time converted from UTC to specific country timezone. Am I missing something?

Related

Why django timezone offset is different?

Django 3.2.10, Python 3.9
settings.py
TIME_ZONE = 'Europe/Moscow'
script.py
from django.utils import timezone
tzinfo = timezone.localtime().tzinfo # <class 'pytz.tzfile.Europe/Moscow'>
tz = timezone.get_current_timezone() # <class 'pytz.tzfile.Europe/Moscow'>
dtz = timezone.get_default_timezone() # <class 'pytz.tzfile.Europe/Moscow'>
datetime_object = timezone.now()
print(datetime_object) # 2022-03-29 03:34:42.244830+00:00
print(datetime_object.replace(tzinfo=tzinfo)) # 2022-03-29 03:34:42.244830+03:00
print(datetime_object.replace(tzinfo=tz)) # 2022-03-29 03:34:42.244830+02:30
print(datetime_object.replace(tzinfo=dtz)) # 2022-03-29 03:34:42.244830+02:30
+0230 is not +0300, and the correct offset for this time zone is +0300.
Using tzinfo when building timezone-aware datetimes is (from what I heard) a bad practice and can lead to bugs.
With
`TIME_ZONE = 'Europe/Moscow'
you should use make_aware:
from django.utils import timezone
from datetime import datetime, time
local_now = timezone.localtime()
time_on_the_clock = time(5, 2)
timezone_aware_time = timezone.make_aware(datetime.combine(local_now, time_on_the_clock))
print(timezone_aware_time)
or using pytz:
from datetime import datetime
from pytz import timezone
datetime_object = datetime.now()
moscow_time = timezone('Europe/Moscow').localize(datetime_object, is_dst=None)
print(moscow_time)

Timezone is UTC infact of changing it in settings.py file

My app is showing the timezone.now() as UTC time when I see it in Heroku scheduler. Also I built a custom manage.py command to test it but it still shows UTC time.
Here is my settings.py
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Kolkata'
USE_I18N = True
USE_L10N = True
USE_TZ = True
Here is my personalied manage.py command
managemet/commaands/abhiwaqt.py
from django.core.management.base import BaseCommand, CommandError
from django.apps import apps
from Directory.utils import *
class Command(BaseCommand):
help="Refresh models and its fields."
def handle(self,*args, **options):
try:
print(timezone.now())
except:
raise CommandError("Something went wrong")
Infact of setting TIME_ZONE='Asia/Kolkata' I am getting this issue.
It is probably good practice to keep your back end using UTC so everything is uniform and handles daylight savings and you simply handle the changes when displaying to the user in templates or views. If you want timezone support (since it is disabled by default) use the setting USE_TZ = True. Take a look at the docs for more in depth explanation on this topic.enter link description here

Get Timezone to take effect

I am going through the Django tutorial.
I thought the TIME_ZONE in settings.py was of form 'UTC-5', but it isn't.
I replaced it with 'America/Chicago'
However, when I do:
python manage.py shell
from django.utils import timezone
timezone.now()
I get 'UTC'
How do I get the timezone to take effect?
It can be confusing. If you run the code below, you will see that it is set, but it won't output as you expect:
from django.utils import timezone
timezone.get_current_timezone() # Should be 'America/Chicago'
timezone.now() # should show UTC
If you want it to output in the shell with your set timezone, use timezone.localtime()
from django.utils import timezone
timezone.localtime()

Timezone It works locally but not in pythonanywhere (DJango)

I have a queryset to list today's sales
from django.utils import timezone
class VentaToday(ListView):
queryset = Venta.objects.filter(fecha=timezone.now()).order_by('-id')
template_name = 'venta/venta_today.html'
In local, this works correctly but in production (Pythonanywhere) the sales of the previous day keep appearing. To fix it, I have to go to the pythonanywhere panel and click on the ** reload ** button to solve the problem.
I changed the server time:
Image of server time
Configuration of the django project:
LANGUAGE_CODE = 'es-pe'
TIME_ZONE = 'America/Lima'
USE_I18N = True
USE_L10N = True
USE_TZ = True
Is it a server cache problem? or something am I doing wrong?
UPDATE
config WSGI:
# +++++++++++ DJANGO +++++++++++
# To use your own django app use code like this:
import os
import sys
os.environ["TZ"] = "America/Lima"
#
## assuming your django settings file is at '/home/dnicosventas/mysite/mysite/settings.py'
## and your manage.py is is at '/home/dnicosventas/mysite/manage.py'
path = '/home/dnicosventas/dnicos-ventas'
if path not in sys.path:
sys.path.append(path)
#
os.environ['DJANGO_SETTINGS_MODULE'] = 'DnicosVentas.settings'
#
## then, for django >=1.5:
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
## or, for older django <=1.4
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
and my console:
export TZ="/usr/share/zoneinfo/America/Lima"
Even so, after 12 a.m., yesterday's sales keep appearing until I click on the reload button in the pythonanywhere panel.
Views.py:
class VentaToday(ListView):
today = datetime.now(pytz.timezone('America/Lima'))
queryset = Venta.objects.filter(fecha=today).order_by('-id')
template_name = 'venta/venta_today.html'
Image of the reload button
Solution by Giles Thomas:
class VentaToday(ListView):
template_name = 'venta/venta_today.html'
def get_queryset(self):
return Venta.objects.filter(fecha=datetime.now(pytz.timezone('America/Lima'))).order_by('-id')
TLDR: I had the same issue. I fixed it by changing TIME_ZONE='' to TIME_ZONE='UTC', in the settings.py file in project folder of pythonanywhere.
Python by default uses pytz.timezone(settings.TIME_ZONE), to initiate the time zone of the webapp, and since by default pythonanywhere doesnt initiate this variable, leaving it to the end user to do it, as per their requirements. So initiate your TIME_ZONE, as per your needs, which may do the trick.
You could also try looking in your project log files, for more information on this.

Not naive datetime (tzinfo is already set)

I use django celery in my django app and I'm experiencing this error:
ValueError: Not naive datetime (tzinfo is already set) in djcelery.utils in make_aware
How to fix this?
I think it's a bug from django-celery when they upgrade their version. But by the way, put this in your init.py where your settings.py located.
# Patch the djcelery/snapshot cause it's broken
import datetime
from django.utils.timezone import is_aware
import djcelery.snapshot
orig_maybe_make_aware = djcelery.snapshot.maybe_make_aware
def new_maybe_make_aware(value):
if isinstance(value, datetime.datetime) and is_aware(value):
return value
return orig_maybe_make_aware(value)
djcelery.snapshot.maybe_make_aware = new_maybe_make_aware