转换时间戳时区的好方法是什么?

What's a good way of converting timezone of a timestamp?

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

我已经尝试了一些方法,但似乎没有 clean/short 转换它的方法。

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

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 并对其进行格式化,我必须执行以下操作,每个操作都接受一个日期时间对象,但 return 一个字符串。

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

是否有 clean/short 方法可以在不在字符串和日期时间之间来回转换的情况下获得正确的输出?

非常感谢。

由于内在的 deprecation of pytz, I'd suggest to use dateutil. The usage of dateutil also transforms nicely to Python 3.9's 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