Why does time still show with UTC time zone instea

2020-05-01 04:35发布

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

1条回答
贪生不怕死
2楼-- · 2020-05-01 04:57

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")
查看更多
登录 后发表回答