[Fixed]-Converting time in django

1👍

In templates, Django will automatically convert your model dates (stored as UTC) to the current time zone. The current time zone is set by settings.TIMEZONE unless you explicitly change it somewhere else. You don’t even need to use special template tags. This will convert fine:

{{ MyModel.my_date }}

Outside of templates, there is a tool called localtime that you can use to do the same conversion.

from django.utils.timezone import localtime

...
local_date = localtime(MyModel.my_date)
print( str(MyModel.my_date) )    # UTF time
print( str(local_date) )         # local time

The datetime returned by localtime is time zone aware. If you ever need a time zone naive datetime, you can convert it like this:

my_date = localtime(MyModel.my_date).replace(tzinfo=None)

0👍

If, in settings.py we have the following:

from pytz import timezone
LOCAL_TZ = pytz.timezone('CST6CDT') # asume that local timezone is central, but you can use whatever is accurate for your local

Now, you can use this to convert from utc time to local

import pytz
from django.conf import settings

def to_local_dttm(utc_dttm):
    return utc_dttm.astimezone(settings.LOCAL_TZ)

def to_utc_dttm(local_dttm):
    return local_dttm.astimezone(pytz.utc)

Leave a comment