Reputation: 4365
What am I missing here?
Why does this...
import datetime
start_date = '2020-10-01T00:00:00Z'
start_date_obj = datetime.datetime.strptime(start_date, '%Y-%m-%dT%H:%M:%SZ')
print(start_date_obj)
...result in: 2020-10-01 00:00:00
...instead of: 2020-10-01T00:00:00Z
?
Where is the "T" and "Z" in the output?
Upvotes: 0
Views: 2853
Reputation: 25554
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
Upvotes: 1
Reputation: 4365
Disregard. Apparently I need to convert from datetime
object back to string(?) to make this print nicely?
import datetime
start_date = '2020-10-01T00:00:00Z'
start_date_obj = datetime.datetime.strptime(start_date, '%Y-%m-%dT%H:%M:%SZ')
start_date_printable = datetime.datetime.strftime(start_date_obj, '%Y-%m-%dT%H:%M:%SZ')
print(start_date_printable)
Results in: 2020-10-01T00:00:00Z
Upvotes: 1