0

I have been using the following directive to decode this string.

datetime.strptime('2021-07-09T21:01:49.926811Z', '%Y-%m-%dT%H:%M:%S.%f%Z')

But I get this error message:

ValueError: time data '2021-07-09T21:01:49.926811Z' does not match format '%Y-%m-%dT%H:%M:%S.%f%Z'

What is the right format ?

FObersteiner
  • 16,957
  • 5
  • 24
  • 56
Roland
  • 11
  • 3

1 Answers1

0

You have to replace '%Z' by 'Z':

>>> datetime.strptime('2021-07-09T21:01:49.926811Z', '%Y-%m-%dT%H:%M:%S.%fZ')
datetime.datetime(2021, 7, 9, 21, 1, 49, 926811)

Or use fromisoformat (and remove the trailing Z):

>>> datetime.fromisoformat(s[:-1])
datetime.datetime(2021, 7, 9, 21, 1, 49, 926811)

Or use dateutil which is the most flexible:

# from dateutil import parser
>>> parser.parse(s)
datetime.datetime(2021, 7, 9, 21, 1, 49, 926811, tzinfo=tzutc())
Corralien
  • 70,617
  • 7
  • 16
  • 36
  • since Python treats naive datetime as *local time*, using a literal "Z" in the parsing directive actually gives a wrong result I think. Z denotes zulu time / UTC. dateutil's parser sets it correctly. – FObersteiner Jul 25 '21 at 16:17