You want to convert the string to a datetime like object first. The problem with your string is that the timezone is in a format that datetime doesn't recognise.
You could use pandas Timestamp
import pandas as pd
ts = pd.Timestamp(string).tz_convert("UTC")
output = ts.strftime("%Y-%m-%dT%H:%M:%S")
Alternatively, if you don't want to install/use Pandas, could convert the string format, and then use datetime.
import datetime
import pytz
import re
# Remove the ':' from the timezone, if it's there.
string = re.sub("\+(?P<hour>\d{2}):(?P<minute>\d{2})$", "+\g<hour>\g<minute>" , string)
# Create the datetime object.
dt = datetime.datetime.strptime(string, "%Y-%m-%dT%H:%M:%S%z")
# Convert to UTC
dt = dt.astimezone(pytz.UTC)
output = dt.strftime("%Y-%m-%dT%H:%M:%S")
If you're using python 2.7, and can't specify %z when calling strptime the standard workaround is to do this:
def parse(string):
dt = datetime.strptime(string[0:19],'%Y-%m-%dT%H:%M:%S')
if string[19] == "+":
dt -= datetime.timedelta(hours=int(string[20:22]),
minutes=int(string[22:]))
elif t[19]=='-':
dt += datetime.timedelta(hours=int(string[20:22]),
minutes=int(string[22:]))
return dt
The advantage of the methods above, vs Stefano's answer, is that they will work with an arbitrary offset. Not just for four and half hours.