0

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?

SeaDude
  • 3,725
  • 6
  • 31
  • 68
  • 2
    Note that when you call `print(datetime_object)`, the `__str__` method of the datetime object is called - this happens to give you isoformat with space as date/time separator. It's just a matter of display, that's all. If you want a string in a specific format, see my answer. – FObersteiner Nov 02 '20 at 08:16
  • Does this answer your question? [How do I parse an ISO 8601-formatted date?](https://stackoverflow.com/questions/127803/how-do-i-parse-an-iso-8601-formatted-date) – FObersteiner Nov 02 '20 at 08:16

2 Answers2

1

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
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
0

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

SeaDude
  • 3,725
  • 6
  • 31
  • 68