the Z denotes UTC, so you should parse to an aware datetime object using either strptime
with the %z
directive:
from datetime import datetime
s = '2020-10-01T00:00:00Z'
dt = datetime.strptime(s, '%Y-%m-%dT%H:%M:%S%z')
print(dt)
# 2020-10-01 00:00:00+00:00
or fromisoformat
with a little hack:
dt = datetime.fromisoformat(s.replace('Z', '+00:00'))
print(dt)
# 2020-10-01 00:00:00+00:00
You can do the same thing when converting back to string:
out = dt.isoformat().replace('+00:00', 'Z')
print(out)
# 2020-10-01T00:00:00Z
strftime
won't give you Z
but for example UTC
:
out = dt.strftime('%Y-%m-%dT%H:%M:%S %Z')
print(out)
# 2020-10-01T00:00:00 UTC