【问题标题】:How to convert a Zulu timestamp to local time zone? [duplicate]如何将祖鲁时间戳转换为本地时区? [复制]
【发布时间】:2021-05-31 11:12:30
【问题描述】:

我知道有人以不同的形式提出过这个问题,但我没有找到我需要的东西。我正在寻找一种使用 Python 将以下日期/时间转换为我的本地时区的方法。请注意“Z”的时区和日期和时间之间的“T”,这让我很反感。

"startTime": "2021-03-01T21:21:00.652064Z"

【问题讨论】:

  • 参见例如here 如何从 UTC 转换到本地时间,here 获取有关您所拥有格式的背景信息。

标签: python date datetime time timezone


【解决方案1】:

datetime 模块是你的朋友。您似乎正在处理 ISO 格式的日期时间戳。 datetime 模块有一个类方法可以从 ISO 格式的字符串生成 datetime 对象。

from datetime import datetime
dateinput = "2021-03-01T21:21:00.652064Z"
stamp = datetime.fromisoformat(dateinput)

但是在这里你会得到一个错误,因为尾随的“Z”不太正确。如果你知道它会一直存在,只需去掉最后一个字符。否则,您可能必须先进行一些字符串操作。

stamp = datetime.fromisoformat(dateinput[:-1])

另请参见 strptime() 类方法以从任意格式的字符串中获取日期时间对象。

希望这会有所帮助...

【讨论】:

  • 而不是切掉Z,更好地正确解析为UTC,参见例如stackoverflow.com/a/62769371/10197418。顺便提一句。您的答案缺少从 UTC 到当地时间的方法 ;-)
  • 我在运行时不断收到此错误。 AttributeError:类型对象'datetime.datetime'没有属性'fromisoformat'
  • @Karl:您使用的是哪个 Python 版本? fromisoformat 是 Python 3.7+ 功能
  • 版本 Python 3.8.3
  • 更正,Python 3.6
【解决方案2】:

datetime 和 pytz 模块!也取决于您的需要,但下面是没有毫秒部分的日期和时间对象以及到柏林时区的简单转换。

import datetime
from pytz import timezone
berlin_timezone = pytz.timezone('Europe/Berlin')

your_time = datetime.datetime.strptime(startTime.split(".")[0], "%Y-%m-%dT%H:%M:%S")
your_time_utc = your_time.astimezone(berlin_timezone)

【讨论】:

  • OP 的输入指定了 UTC (Z) - 您的回答没有考虑到这一点,并且会给出错误的结果。此外,Python 3.9+ 可以自己很好地处理时区,请参阅zoneinfo
猜你喜欢
  • 1970-01-01
  • 2021-03-23
  • 2019-03-09
  • 2017-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-15
  • 2018-04-17
相关资源
最近更新 更多