【问题标题】:Convert UTC date string to PST and then subtract 12 hours from it将 UTC 日期字符串转换为 PST,然后从中减去 12 小时
【发布时间】:2022-01-01 10:08:45
【问题描述】:

我收到的字符串是 ISO 格式的 UTC 日期,例如,

2021-11-21T12:16:42Z

我希望将这些日期转换为 PST,然后从中减去 12 小时。

import datetime
time_list_utc=2021-11-21T12:16:42Z
time_list_pst=time_list_utc.convert(pst)
print(time_list_pst-8hours)

我是日期时间操作的新手,因此非常感谢任何输入

【问题讨论】:

标签: python python-3.x date datetime iso


【解决方案1】:

从 Python 3.9 开始使用 datetimetzinfotimedelta 模块:

from datetime import datetime, timedelta
from zoneinfo import ZoneInfo

s = '2021-11-21T12:16:42Z'

# Convert to datetime (UTC)
dt_utc = datetime.strptime(utc, "%Y-%m-%dT%H:%M:%S%z")

# Convert to PST
dt_pst = dt_utc.astimezone(ZoneInfo('US/Pacific'))

# Subtract 12 hours
dt = dt_pst - timedelta(hours=12)

输出:

>>> dt
datetime.datetime(2021, 11, 20, 16, 16, 42, tzinfo=zoneinfo.ZoneInfo(key='US/Pacific'))

>>> dt_pst
datetime.datetime(2021, 11, 21, 4, 16, 42, tzinfo=zoneinfo.ZoneInfo(key='US/Pacific'))

>>> dt_utc
datetime.datetime(2021, 11, 21, 12, 16, 42, tzinfo=datetime.timezone.utc)

【讨论】:

  • @Cyber​​_Tron。能解决你的问题吗
猜你喜欢
  • 2020-03-25
  • 2011-08-29
  • 2021-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多