【问题标题】:What's a good way of converting timezone of a timestamp?转换时间戳的时区的好方法是什么?
【发布时间】:2021-01-05 22:39:37
【问题描述】:

我有一个格式如下的字符串:09/20/2020 10:30 AM 该时间戳位于东部时区。 我需要获取等效的 UTC,但采用以下 ISO 格式:2020-09-20T14:30:00.0000Z

我已经尝试了一些东西,但似乎没有一种干净/简短的转换方法。

到目前为止我已经尝试过:

dtSept = "09/20/2020 10:00 PM"
dtSeptTZ = pytz.timezone('US/Eastern').localize(datetime.datetime.strptime(dtSept, "%m/%d/%Y %I:%M %p")).isoformat(timespec='milliseconds')

dtSeptTZ此时是一个字符串对象。 如果我必须转换它的 TimeZone 并对其进行格式化,我必须执行以下操作,每个都采用 datetime 对象但返回一个字符串。

dtSeptTZ.astimezone(pytz.timezone('Etc/UTC'))
dtSeptTZ.strftime("%Y-%m-%dT%I:%M.%fZ")

是否有一种简洁/简短的方法来获得正确的输出,而无需在字符串和日期时间之间来回转换?

非常感谢。

【问题讨论】:

  • 简短回答:不。您将 必须 将字符串转换为 datetime 对象以转换为另一个时区。在我看来,其他任何事情都非常容易出错。

标签: python-3.x datetime timezone pytz


【解决方案1】:

由于固有的deprecation of pytz,我建议使用dateutildateutil 的用法也可以很好地转换为 Python 3.9 的 zoneinfo

from datetime import datetime, timezone
from dateutil.tz import gettz

dtSept = "09/20/2020 10:00 PM"
# string to datetime object
dt = datetime.strptime(dtSept, "%m/%d/%Y %I:%M %p")
# set tzinfo to appropriate time zone; (!) use "localize" instead with pytz timezone class
dt = dt.replace(tzinfo=gettz('US/Eastern'))
# to UTC (could use any other tz here)
dt_utc = dt.astimezone(timezone.utc)

# to ISO format string:
print(dt_utc.isoformat())
>>> 2020-09-21T02:00:00+00:00

【讨论】:

    猜你喜欢
    • 2021-06-14
    • 2011-12-15
    • 1970-01-01
    • 2021-09-22
    • 2015-11-04
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    • 2019-09-11
    相关资源
    最近更新 更多