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

标签 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 中显示 UTC 时间[0].checkintime。

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

但是,我无法通过破解来显示它。

最佳答案

如果您有日期时间和用户的时区,则可以创建 template filter它接受一个日期时间对象,执行所需的计算,然后打印字符串。

如果您的问题实际上是关于将时区应用于简单的日期时间对象,那么请查看 pytz (relevant 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')

关于python - SQLAlchemy Date Time 对象可以在 Flask 中显示本地时区吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29110178/

相关文章:

python - 为使用 Flask 发送的电子邮件创建一个安全的退订链接

python - Azure 部署未安装requirements.txt 中列出的Python 包

php - 在 PHP Web 应用程序中使用时区

javascript - 使用javascript将GMT转换为IST(印度标准时间)?

php - 根据服务器 UTC 偏移量和用户 UTC 偏移量更改当前用户时区

Python:尝试通过 SSH 执行命令时 Paramiko 挂起

python - AWS Glue 中的可选作业参数?

python - Pandas 在我的数据中按第一天重新采样

python - STATIC_ROOT 和 MEDIA_ROOT 正确配置

python - Flask render_template 上下文在蓝图中为 None