Very late reply but for posterity, if you really want to parse it with strptime
you can use %z
https://intellipaat.com/community/58366/the-strptime-example-for-datetime-with-tz-offset
Example:
datetime_string = "2021-01-01T10:25:00+00:00"
obj = datetime.strptime(datetime_string, "%Y-%m-%dT%H:%M:%S%z")
print(repr(obj))
>>> datetime.datetime(2021, 1, 1, 10, 25, tzinfo=datetime.timezone.utc)
datetime_string = datetime.strftime(obj, "%Y-%m-%dT%H:%M:%S%z")
print(datetime_string)
>>> 2021-01-01T10:25:00+0000
although notice the offset is now shown as +0000
which may be enough for you.
if you still insist on the output being the ISO 8601 format, and insist on using strftime
to bring the format back to +00:00, you have to use a custom tzinfo
object.
Example:
class TZ1(tzinfo):
def utcoffset(self, dt): return timedelta(hours=0)
def dst(self, dt): return timedelta(0)
def tzname(self, dt): return "+00:00"
datetime_string = "2021-01-01T10:25:00+00:00"
obj = datetime.strptime(datetime_string, "%Y-%m-%dT%H:%M:%S%z").replace(tzinfo=TZ1())
>>> datetime.datetime(2021, 1, 1, 10, 25, tzinfo=<__main__.TZ1 object at 0x7ff6e1c41f50>)
datetime_string = datetime.strftime(obj, "%Y-%m-%dT%H:%M:%S%Z")
print(datetime_string)
>>> 2021-01-01T10:25:00+00:00
This example is obviously hardcoded for UTC+0, but you can apply some logic based on the dt
argument if necessary.
This approach can be quite useful (as opposed to the magic in the dateutil
library) if you are setting up strict rules for dates and times in data processing from untrustworthy sources, to be used with validation, coercion etc. as you can set rigid inputs and outputs.