A
A
Andrey Salnikov2018-05-15 14:07:13
Django
Andrey Salnikov, 2018-05-15 14:07:13

What is the correct way to display DateTimefield in Django?

In the settings is:

TIME_ZONE = 'Europe/Samara'
USE_TZ = True

In the model:
class A(models.Model):
    created = models.DateTimeField()

    def __str__(self):
        return 'Заявка от {}'.format(self.created.strftime('%d.%m.%Y %H:%M'))

It is displayed :
Заявка от 15.05.2018 09:30
And I need it to be output like this:
Заявка от 15.05.2018 13:30
If I write like this:
def __str__(self):
    return self.created

Then it is displayed:
15 мая 2018 13:30
Question:
How to write the code correctly so that everything is displayed as I need with the correct TZ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tema_sun, 2018-05-15
@Shshzik

Django stores such objects in UTC, and applies the time zone at the time of rendering to the template. Those. you have to do it by hand.

from django.utils import timezone
tz = timezone.get_default_timezone()

class A(models.Model):
    created = models.DateTimeField()
    def __str__(self):
        return 'Заявка от {}'.format(self.created.astimezone(tz).strftime('%d.%m.%Y %H:%M'))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question