如何使用以这种格式给出的时区偏移量更新 Python 日期时间对象:“+0300”?

How to update Python datetime object with timezone offset given in such format: "+0300"?

给定一个这样的 datetime.datetime 对象:

datetime.datetime(2022, 2, 22, 9, 24, 20, 386060)

我得到这样格式的客户端时区偏移量:“+0300”并且需要表示考虑到这个偏移量的 datetime.datetime 对象。

例如,上面的对象应该是这样的:

datetime.datetime(2022, 2, 22, 12, 24, 20, 386060)

IIUC,您有一个表示 UTC 的日期时间对象,并希望转换为 3 小时的 UTC 偏移量。你可以这样做

import datetime

dt = datetime.datetime(2022, 2, 22, 9, 24, 20, 386060)

# assuming this is UTC, we need to set that first
dt = dt.replace(tzinfo=datetime.timezone.utc)

# now given the offset
offset = "+0300"

# we can convert like
converted = dt.astimezone(datetime.datetime.strptime(offset, "%z").tzinfo)
>>> converted
datetime.datetime(2022, 2, 22, 12, 24, 20, 386060, tzinfo=datetime.timezone(datetime.timedelta(seconds=10800)))