Skip to content Skip to sidebar Skip to footer

Utc To Local Timezone In A Flask/jinja Template

I know this has been asked before, and I'm still pulling my hair out trying to figure this one out. I've tried pytz, dateutil, and now flask_moment. Still having problems convertin

Solution 1:

This is what ended up working for me, in this particular case, and I'm still not sure if it is going to give incorrect info during DST, but we'll see.

import pytz
from pytz import timezone
import tzlocal 

defdatetimefilter(value, format="%I:%M %p"):
    tz = pytz.timezone('US/Eastern') # timezone you want to convert to from UTC
    utc = pytz.timezone('UTC')  
    value = utc.localize(value, is_dst=None).astimezone(pytz.utc)
    local_dt = value.astimezone(tz)
    return local_dt.strftime(format)

flask_app.jinja_env.filters['datetimefilter'] = datetimefilter

Then my jinja2 template looks like:

{% for data in items %}
...
<td>{{data.loggedInBy}}</td><td>{{data.timeIn | datetimefilter }}</td>
...
{% endfor %}

If there's any way to improve on this, I'm open to suggestions, but so far, this is the only way that I've found that works.

Solution 2:

Localize is not going to change the timezone, but rather add the timezone information to a naive datetime object. You say your datetime is coming from SQL and is in UTC, but is is a timezone aware datetime object? If value is a datetime object that is aware it is UTC and not a naive datetime object you should change the timezone like this

tz = pytz.timezone('US/Eastern')  # timezone you want to convert to from UTC
local_dt = value.astimezone(tz)
return local_dt.strftime(format)

If you get an error ValueError: astimezone() cannot be applied to a naive datetime then your value is a naive datetime object and you could make it time zone aware (as UTC) 1st and then get your localized datetime like this.

tz = pytz.timezone('US/Eastern')
utc = pytz.timezone('UTC')
tz_aware_dt = utc.localize(value)
local_dt = tz_aware_dt.astimezone(tz)
return local_dt.strftime(format)

There are a number of ways you could check to see if your datetime object is naive or not. For instance, if it is aware of it's timezone value.tzname() will return the name of the timezone, otherwise it will return none.

Timezone aware: datetime.datetime(2016, 1, 1, 4, 28, 26, 149703, tzinfo=<DstTzInfo 'US/Eastern' EST-1 day, 19:00:00 STD>)

Naive datetime object: datetime.datetime(2016, 1, 1, 9, 28, 26, 149703)

Solution 3:

Flask-Moment is good to be used in this case. See the link for the detailed instruction.

Post a Comment for "Utc To Local Timezone In A Flask/jinja Template"