Parse the input, set the timezone, convert to UTC, then format the output.
from datetime import datetime
from zoneinfo import ZoneInfo
# May need to "pip install tzdata" for latest timezone support.
# It is used by ZoneInfo. See https://docs.python.org/3/library/zoneinfo.html
UTC = ZoneInfo('UTC')
LOCAL = ZoneInfo('US/Pacific')
s = '2022-07-20 1:09:51'
dt = datetime.strptime(s, '%Y-%m-%d %H:%M:%S')
local = dt.replace(tzinfo=LOCAL)
utc = local.astimezone(UTC)
print('naive ',dt)
print('local ',local)
print('UTC ',utc)
print('ISO ',utc.isoformat())
print('custom',utc.strftime('%Y-%m-%dT%H:%M:%SZ'))
Output:
naive 2022-07-20 01:09:51
local 2022-07-20 01:09:51-07:00
UTC 2022-07-20 08:09:51+00:00
ISO 2022-07-20T08:09:51+00:00
custom 2022-07-20T08:09:51Z
If you want PM as you implied use either:
s = '2022-07-20 1:09:51pm'
dt = datetime.strptime(s, '%Y-%m-%d %I:%M:%S%p')
or
s = '2022-07-20 13:09:51'
dt = datetime.strptime(s, '%Y-%m-%d %H:%M:%S')
To get a final result of:
custom 2022-07-20T20:09:51Z