mb52089
mb52089

Reputation: 872

django - str of datetime with user's timezone

I'm trying to build a blurb of text that I'll ultimately send in an SMS message. The blurb includes text of a datetime object that has UTC as the timezone, but needs the text to be localized for the user's timezone instead. I have the user's timezone stored in the db.

I know that I can use timezone.activate() and timezone.deactivate() to change the current timezone, but I don't know if that's the best thing to do, when all I want is the text of the datetime to print out in the user's local timezone. I don't know if changing the current timezone will have unwanted system consequences, even if just for a short time.

Upvotes: 2

Views: 274

Answers (1)

BluesRockAddict
BluesRockAddict

Reputation: 15683

Activating timezone using timezone.activate() will only affect current request, so there is really no "unwanted system consequences" to worry about.

By activating the timezone in middleware:

from django.utils import timezone

class TimezoneMiddleware(object):
    def process_request(self, request):

        if request.user.is_authenticated():
            timezone.activate(request.user.get_profile().timezone)

you'll be able to render user's local time by using {{ datatime }} parameter in your SMS template.

Upvotes: 3

Related Questions