Python 3.x 什么';这是转换时间戳时区的好方法吗?

Python 3.x 什么';这是转换时间戳时区的好方法吗?,python-3.x,datetime,timezone,pytz,Python 3.x,Datetime,Timezone,Pytz,我有一个以下格式的字符串:09/20/2020上午10:30 那个时间戳在东部时区。 我需要获得UTC等效值,但采用以下ISO格式:2020-09-20T14:30:00.0000Z 我尝试了一些方法,但似乎没有一个简单/快捷的方法来转换它 到目前为止,我已经尝试: dtSept = "09/20/2020 10:00 PM" dtSeptTZ = pytz.timezone('US/Eastern').localize(datetime.datetime.strptime(

我有一个以下格式的字符串:09/20/2020上午10:30 那个时间戳在东部时区。 我需要获得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')
dtseptz
此时是一个字符串对象。 如果我必须转换它的时区并格式化它,我必须执行以下命令,每个命令都接受一个datetime对象,但返回一个字符串

dtSeptTZ.astimezone(pytz.timezone('Etc/UTC'))
dtSeptTZ.strftime("%Y-%m-%dT%I:%M.%fZ")
有没有一种干净/快捷的方法可以获得正确的输出,而不必在字符串和日期时间之间来回转换

非常感谢。

由于内在原因,我建议使用。
dateutil
的使用也很好地转换为Python 3.9


简短回答:否。您必须将字符串转换为
datetime
对象才能转换为另一个时区。在我看来,其他任何东西都很容易出错。非常感谢!
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