Django using TIME_ZONE to display local time

It took me a while to figure out how to do this correctly. There is too much noise from google search… Here are my settings for everything to display correctly in my admin site w/ Django 1.8.

settings.py

USE_TZ = True
TIME_ZONE = 'US/Pacific'
HUMAN_TIME_FMT = '%Y-%m-%d %H:%M:%S %p'

HUMAN_TIME_FMT is optional, I put it there for my own usage.

models.py

from django.conf import settings
from django.db import models
from django.utils import timezone

class Sync(models.Model):

    sync_start = models.DateTimeField('sync starts')
    sync_end = models.DateTimeField('sync ends')
    
    def __str__(self):
        fmt = settings.HUMAN_TIME_FMT
        my_dt1 = timezone.localtime(self.sync_start).strftime(fmt)
        my_dt2 = timezone.localtime(self.sync_end).strftime(fmt)
        return 'From ' + my_dt1 + ' => ' + my_dt2

More to read:
# https://docs.djangoproject.com/en/1.8/ref/settings/#std:setting-TIME_ZONE
# http://en.wikipedia.org/wiki/List_of_tz_database_time_zones
# http://strftime.org/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s