【问题标题】:Display datetime local timezones显示日期时间本地时区
【发布时间】:2021-07-09 20:45:50
【问题描述】:

我对此很陌生,所以不确定它是如何工作的,我已经尝试阅读,但我认为我只需要一个简单的解释来解释什么可能是一个基本问题。

通过 API,我得到了棒球赛程表,日期以日期时间对象的形式出现,例如 '2021-04-15T02:10:00.000Z'

我知道 Z 表示 UTC 时间,但它会以本地时间显示用户所在的位置吗?

如果我将它作为 DateTimeField 保存在我的模型中,我如何将它作为用户本地时间传递给我的模板?

提前感谢您的帮助!

【问题讨论】:

  • 我已经为第一部分添加了答案;你问题的第二部分读起来好像最好至少提出一个单独的具体问题(“DateTimeField”是什么意思,你的“模型”是什么,哪个“模板”,什么“用户”,如何获取用户的时区?)。

标签: python datetime timezone pytz


【解决方案1】:

解析为日期时间 - 您的输入已根据ISO 8601 很好地格式化,您可以像我在here 中显示的那样解析为日期时间对象。

from datetime import datetime

s = "2021-04-15T02:10:00.000Z"
dtobj = datetime.fromisoformat(s.replace('Z', '+00:00'))

print(repr(dtobj))
# datetime.datetime(2021, 4, 15, 2, 10, tzinfo=datetime.timezone.utc)

转换为当地时间 - 现在您可以使用astimezone 方法转换为您的机器配置为使用的时区(另请参阅this) :

dt_local = dtobj.astimezone(None) # None here means 'use local time from OS setting'

print(repr(dt_local))
# datetime.datetime(2021, 4, 15, 4, 10, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), 'Mitteleuropäische Sommerzeit'))

# Note: my machine is on Europe/Berlin, UTC+2 on the date from the example

转换到另一个时区 - 如果您想转换到另一个时区,请获取一个时区对象,例如来自zoneinfo lib (Python 3.9+) 并进行如下转换:

from zoneinfo import ZoneInfo

time_zone = ZoneInfo('America/Denver')
dt_denver= dtobj.astimezone(time_zone)

print(repr(dt_denver))
# datetime.datetime(2021, 4, 14, 20, 10, tzinfo=zoneinfo.ZoneInfo(key='America/Denver'))

请参阅here 如何获取可用时区列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 2018-05-08
    • 1970-01-01
    • 2014-02-22
    • 1970-01-01
    相关资源
    最近更新 更多