Reputation: 4371
I'm saving all timing to my database in 'UTC' time zone, but I want every user to see this value converted to his own timezone. is it possible to be used in Django?
my settings.py :
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
Here is what I tried:
{% load tz %}
<p>
Leave on {{ request.date_time.date|localtime }} at {{ request.date_time.time|localtime }}
</p>
But it gives me a blank result, and when I remove the |localtime
part, it shows it in the UTC format. any help with this?
Upvotes: 1
Views: 2119
Reputation: 29
def get_publish_timezone(self):
import pytz
return self.publish.astimezone(pytz.timezone(self.author.get_timezone_str())).replace(tzinfo=None)
here get_timezone_str()
is the one who convert id
of timezone to string like 'Asia/Kolkata
'
def get_timezone_str(self):
from .timezone import from_system
try:
return from_system[self.timezone]
except KeyError:
return 'UTC'
from_system
is dict
some demos are below.
from_system = {0: 'America/Puerto_Rico',
1: 'America/New_York',
2: 'America/Chicago',
3: 'America/Denver',
}
Upvotes: -1
Reputation: 6598
localtime
template tag does not operate on date
object. It operates on datetime
object. You should apply it on datetime object and then chain with date filter.
{{ request.date_time|localtime|date:'Y-m-d' }} at {{ request.date_time|localtime|date:'H:i' }}
Or you can do
{% with local=request.date_time|localtime %}
<p>
Leave on {{ local|date:'Y-m-d' }} at {{ local|date:'H:i' }}
</p>
{% endwith %}
Upvotes: 3
Reputation: 1394
You can also convert your timezone
into the user's timezone
from Django
view
and pass it in context
and use that context
in your template
as below...
views.py
from django.utils import timezone
local_time = timezone.localtime(your_datetime_object)
Now, you can pass local_time
into your context and use it in your template.
For more reference, you can click here
Upvotes: 2