显示日期时间本地时区

Display datetime local timezones

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

从 API 我得到一个棒球赛程表,日期作为日期时间对象出现,像这样 '2021-04-15T02:10:00.000Z'

我知道 Z 表示 UTC 时间,但它会在用户所在的地方显示当地时间吗?

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

在此先感谢您的帮助!

解析为日期时间 - 您的输入格式很好地符合 ISO 8601, you can parse to datetime object like I've shown 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 method to the time zone your machine is configured to use like (see also ):

进行转换
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 库(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如何获取可用时区列表。