Reputation:
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!
Upvotes: 0
Views: 205
Reputation: 1204
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
Upvotes: 1