SQLAlchemy Date Time对象可以在Flask中显示本地时区

时间:2015-03-17 21:36:26

标签: python flask utc

这是我的第一篇Stackoverflow帖子,请原谅我的语法 我试图在SQLAlchemy数据库中没有时区的日期时间戳中显示时间戳,在用户的浏览器中显示时区,而不是UTC。

这是我的python / Flask代码(我是初学者):

首先我查询数据库

    timeclockinfo = TimeClock.query.filter_by(parent_id=current_user.parent_id, user_id=current_user.user_id, closed=1).all()

    #Then I tuple the data
    child_patient = zip(timeclockinfo, user_names, visit_dates )

    #I render the data with Flask
    return render_template('locationcheckinrpt.html', form=form, child_patient=child_patient, timeclockinfo=timeclockinfo, searchForm=searchForm)
    .
    .
    .
    #In the template I have a date time field for the records rendered
    {% for times in child_time %}
          {{  times[0].checkintime.strftime('%Y/%m/%d @ %I:%M %p')    }}
    {% endfor %}

有人可以告诉我如何在浏览器用户时区显示UTC时间[0] .checkintime而不是UTC。

我确实让用户输入他们的时区,因此我减去了适当的小时数。

但是,我无法破解我的方式来展示它。

1 个答案:

答案 0 :(得分:0)

如果你有日期时间和用户的时区,你可以创建一个template filter来获取一个日期时间对象,进行所需的计算,然后打印字符串。

如果您的问题是关于将时区应用于天真的日期时间对象,请查看pytzrelevant section):

from datetime import datetime
from pytz import timezone

tz = timezone('saved_user_timezone')
dt = saved_time_from_db
locl_dt = tz.localize(dt)

要显示带有时区偏移的日期时间,请尝试:

local_dt.replace(hour=local_dt.hour + int(local_dt.utcoffset().total_seconds() / 3600))
local_dt.strftime('your format')
相关问题