Search code examples
pythonflasktimezonejinja2pytz

Flask + Jinja: Convert UTC to Local Timezone


I have a Flask app that stores a user's timezone (from pytz.common_timezones) in a database.

I store records in the DB using a UTC timestamp.

I want to display these records to end-users according to their timezone.

Is it best to:

  1. Iterate through each record and convert the timezone before passing it to render_template?

    --or--

  2. Define a macro within my view that performs this conversion within the template itself?

Are there any best practices for converting a naive timezone to a local timezone?


Solution

  • I think you have two separate questions here. The real question is about how best to manipulate your template - which could be asked about any value manipulation. I'll let someone else answer on that.

    With regard to the second question:

    Are there any best practices for converting a naive timezone to a local timezone?

    That doesn't make a lot of sense. "naive" in the python sense means "unaware of time zone" - so there's not really such a thing as a "naive timezone".

    If you mean converting from a naive datetime to an aware datetime, then the best advice is to be sure to use the localize function, as described in the pytz documentation. Don't try to assign it to the tzinfo property yourself.