0

I have a model that shows a short string in __str__() method of the model

def __str__(self):
    return "Scheduled at %s" % (self.date_time.strftime("%B %d %Y %I:%M %p"))
    #Output: <Task: Scheduled at September 30 2018 12:30 AM>
    # it should have been: <Task: Scheduled at September 29 2018 08:30 PM>

When I go to the Django admin, I see in the title Task: Scheduled at September 30 2018 12:30 AM and in the input it is filled with the correct TIME_ZONE: 20:30:00

settings.py

TIME_ZONE = 'Etc/GMT+4'

USE_I18N = False

USE_L10N = False

USE_TZ = True

He keeps showing time with UTC time zone, however I set TIME_ZONE='Etc/GMT+4 in my settings.

I want time data to be saved in database as UTC and show them with TIME_ZONE, in my case Etc/GTM+4

Eu Chi
  • 533
  • 1
  • 6
  • 22

1 Answers1

3

Django converts datetimes when displaying values with templates. If you want to do the conversion in arbitrary blocks of code, use the localtime() helper:

from django.utils.timezone import localtime

def __str__(self):
    return "Scheduled at %s" % localtime(self.date_time).strftime("%B %d %Y %I:%M %p")
Kevin Christopher Henry
  • 46,175
  • 7
  • 116
  • 102
  • thank you! i set also the TIME_ZONE, is it redundant? `django.utils.timezone.localtime(date_time, pytz.timezone(settings.TIME_ZONE))` – Eu Chi Oct 01 '18 at 16:57
  • 1
    It's redundant. The documentation says that the default value is the current time zone, which is the same as `TIME_ZONE` if you haven't activated another one. – Kevin Christopher Henry Oct 01 '18 at 22:05