You're looking for %z:
>>> datetime.strptime('2020-10-23T11:50:19+00:00', '%Y-%m-%dT%H:%M:%S%z')
datetime.datetime(2020, 10, 23, 11, 50, 19, tzinfo=datetime.timezone.utc)
Beware of some Python version compatibility notes:
Changed in version 3.7: When the %z
directive is provided to the strptime()
method, the UTC offsets can have a colon as a separator between hours, minutes and seconds. For example, '+01:00:00'
will be parsed as an offset of one hour. In addition, providing 'Z'
is identical to '+00:00'
.
More robust approach, it's not strptime
, but it's still in stdlib since Python 3.7:
>>> datetime.fromisoformat('2020-10-23T11:50:19+00:00')
datetime.datetime(2020, 10, 23, 11, 50, 19, tzinfo=datetime.timezone.utc)
As documented this function supports strings in the format:
YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]]
where * can match any single character (not just a T).