Search code examples
pythondjangodjango-timezone

Django: activate() not showing effect


I have the following line in python manager.py shell:

>>> import pytz
>>> from django.utils import timezone
>>> zone = "Asia/Kolkata"
>>> timezone.activate(pytz.timezone(zone))
>>> timezone.now()
datetime.datetime(2014, 12, 17, 1, 52, 0, 411937, tzinfo=<UTC>)

But the output which I get is still using UTC. Should not it be converted into "Asia/Kolkata"?

UPDATE

If i use commands suggested by dazedconfused below:

zone = "Asia/Kolkata"
if zone:
    timezone.activate(pytz.timezone(zone))
else:
    timezone.deactivate()
utc_date = datetime.utcnow()
aware_date = timezone.make_aware(utc_date, timezone.utc)
l_time = timezone.localtime(aware_date, timezone.get_current_timezone())

And now when i try to save it on my database(Mongodb on Mongolab) it gets saved as UTC I have a DateTimeField in my database.

Although when i save it as a simple string it gets saved in current timezone that is "Asia/kolkata" Output as string: 2014-12-17 11:01:53.028852+05:30


Solution

  • It actually successfully sets the current time zone to "Asia/Kolkata"

    You can verify by:

    ...
    >>> timezone.get_current_timezone_name()
    'Asia/Kolkata'
    

    From the django documentation:

    now():

    Returns a datetime that represents the current point in time. Exactly what’s returned depends on the value of USE_TZ:

    • If USE_TZ is False, this will be a naive datetime (i.e. a datetime without an associated timezone) that represents the current time in the system’s local timezone.

    • If USE_TZ is True, this will be an aware datetime representing the current time in UTC. Note that now() will always return times in UTC regardless of the value of TIME_ZONE; you can use localtime() to convert to a time in the current time zone.

    So, if your system's local timezone is 'Asia/Kolkata', you can set USE_TZ to False in your settings.py and the timezone.now() will return what you want.

    Or, you'll have to use localtime() to convert the timezone to yours (continue from your shell results):

    ...
    >>> import datetime
    >>> utc_date = datetime.datetime.utcnow()
    >>> aware_date = timezone.make_aware(utc_date, timezone.utc)
    >>> timezone.localtime(aware_date, timezone.get_current_timezone())
    datetime.datetime(2014, 12, 17, 8, 0, 36, 598113, tzinfo=<DstTzInfo 'Asia/Kolkata' IST+5:30:00 STD>)
    

    Lastly, here's the documentation of the make_aware() function