Get Timezone to take effect - django

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()

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

How do I get dates to display using my settings TIME_ZONE

I'm using Django and Python 3.7. I have the following set in my settings file ...
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Chicago'
USE_I18N = True
USE_L10N = True
USE_TZ = True
I would like for all dates to display using the default time zone I have above. However, when I print out fields like
self.created_on.ctime()
in which "created_on" maps to a PostGres DATETIME field, the date is printed out using a UTC timezone. How can I get this to display using the time zone I have?
TIME_ZONE is a session parameter. Find out more here
and here
from datetime import datetime
from pytz import timezone
self.created_on.astimezone(timezone('America/Chicago'))
looks like you can use the django.utils.timezone.localtime
from django.utils.timezone import localtime
localtime(self.created_on).ctime()

Date time and Date format localization with Django Rest Framework

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?

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