0

I am trying to parse the following datetime value using datetime.strptime:

d = datetime.datetime.strptime('2018-03-26T18:00:00+01:00', "%Y-%m-%dT%H:%M:%Sz")

But getting this error:

ValueError: time data '2018-03-26T18:00:00+01:00' does not match format '%Y-%m-%dT%H:%M:%S%Z'

From my reading of the documentation, %z should equate to the UTC offset, however if I change the format string to end %S%z I get a different error:

ValueError: 'z' is a bad directive in format '%Y-%m-%dT%H:%M:%S%z'

Although this question has been marked as a duplicate, I disagree. I am using Python 2.7 which as noted above does not accept the %z TZ format option, so the approaches mentioned in the comments did not work for me. I finally solved this by using the dateutil module as mentioned in this post: ISO to datetime object: 'z' is a bad directive

I would therefore like to solve my own question although this seems impossible since the question has been marked a duplicate.

btongeorge
  • 421
  • 2
  • 12
  • 23
  • 1
    Remove the `':'` from the timezone – EdChum May 04 '18 at 12:32
  • How best to do this? Should I format the string first and truncate, or? – btongeorge May 04 '18 at 12:33
  • Also note a missing `%`: `%Y-%m-%dT%H:%M:%Sz` should be `%Y-%m-%dT%H:%M:%S%z` – DeepSpace May 04 '18 at 12:34
  • What people have been saying: `datetime.datetime.strptime("2018-03-26T18:00:00+0100", "%Y-%m-%dT%H:%M:%S%z")`. – CristiFati May 04 '18 at 12:36
  • I would do: oldstr = '2018-03-16T18:00:00+01:00', newstr = oldstr.replace(":", ""), d = datetime.datetime.strptime(newstr, "%Y-%m-%dT%H%M%S%z). – tda May 04 '18 at 12:41
  • You could do something like `s = '2018-03-26T18:00:00+01:00' pos = s.rfind(':') s[:pos] + s[pos+1:]` – EdChum May 04 '18 at 12:44
  • When I try to convert the newly formatted datetime using `strptime` I get `ValueError: 'z' is a bad directive in format '%Y-%m-%dT%H:%M:%S%z'`?? - looks like I'm hitting this issue https://stackoverflow.com/questions/20194496/iso-to-datetime-object-z-is-a-bad-directive – btongeorge May 14 '18 at 08:19

0 Answers0