0

Let's say I had the following code

# settings.py in a proper location
...
TIME_ZONE = 'Asia/Seoul'
USE_TZ = True


# models.py in a proper location
class Post(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    def created_formatted(self):
        return self.created.strftime("%Y/%m/%d %H:%M")

Then, I rendered the following django template to html

before formatting: {{ a_post.created }}  # localtime
after formatting: {{ a_post.created_formatted }}  # not localtime

I expected both {{ a_post.created }} and {{ a_post.created_formatted }} have the same timezone, but they don't. I tried to find out how {{ a_post.created }} is rendered to localtime but I'm not sure which part of the django code is the right place to look for yet. (It will be really helpful if you let me know the right part of the django source code to look for). I want to apply the same idea to my created_formatted after I find how the rendering of datetime works in django template.

p.s. I know how to convert timezone-aware datetime to local time in Python. but do how I really have to do this manually for every method that I have? Any advice would be helpful!

1 Answers1

1

From the docs

{% load tz %}

{% localtime on %}
    {{ value }}
{% endlocaltime %}

{% localtime off %}
   {{ value }}
{% endlocaltime %}

If you need a specific timezone

{% load tz %}

{% timezone "Europe/Paris" %}
    Paris time: {{ value }}
{% endtimezone %}

{% timezone None %}
    Server time: {{ value }}
{% endtimezone %}

Docs for localtime, Docs for timezone

at14
  • 1,194
  • 9
  • 16
  • Wow how stupid I am. It was right on the timezone docs. Thank you! Now it seems like localtime tag is on for {{ a_post.created }} but not for {{ a_post.created_formatted }}. Do you know why it works this way? It will be more helpful if you can let me know which part of the django code is responsible for this.. :-) –  Jan 12 '18 at 15:27