Given a datetime.datetime object like that:
datetime.datetime(2022, 2, 22, 9, 24, 20, 386060)
I get client timezone offset in such format: " 0300" and need to represent the datetime.datetime object considering this offset.
For example, the object above should look like this:
datetime.datetime(2022, 2, 22, 12, 24, 20, 386060)
CodePudding user response:
IIUC, you have a datetime object that represents UTC and want to convert to a UTC offset of 3 hours. You can do that like
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)))