【问题标题】:Can SQLAlchemy Date Time object display local time zone in FlaskSQLAlchemy Date Time对象可以在Flask中显示本地时区吗
【发布时间】:2015-03-17 21:36:25
【问题描述】:

这是我的第一篇 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 times[0].checkintime。

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

但是,我无法将其显示出来。

【问题讨论】:

    标签: python flask utc


    【解决方案1】:

    如果你有日期时间和用户的时区,你可以创建一个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 环境中运行良好。我的问题是在网络上的 Flask 模板中呈现当前时区的日期。
    • 这是完美的解决方案。我将 TimeZone 添加到用户帐户并解决了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    • 2011-04-14
    • 1970-01-01
    • 1970-01-01
    • 2016-12-03
    • 2015-09-20
    • 2014-12-25
    相关资源
    最近更新 更多