gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:32:19 25 4
gpt4 key购买 nike

这是我的第一篇 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com