0

I am having some problem converting this datetime format: 2021-08-12T09:15:17+02:00 from string to datetime.

The piece of code I'm using to convert it is the following:

value = datetime.strptime('2021-08-12T09:15:17+02:00', "%Y-%m-%dT%H:%M:%S%z")

Everything seems to work correctly if the python version used is 3.8, while if the version is 3.6 I get the following error:

ValueError: time data '2021-08-12T09:15:17+02:00' does not match format '%Y-%m-%dT%H:%M:%S%z'

How can I solve?

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
Matteo Pasini
  • 1,787
  • 3
  • 13
  • 26
  • 3
    If I remember correctly, Python 3.6 doesn't support the colon `:` in the UTC offset yet, was added with Python 3.7. You can remove it e.g. like `'2021-08-12T09:15:17+02:00'[::-1].replace(":", "", 1)[::-1]`. – FObersteiner Aug 12 '21 at 07:23
  • Ok thank you, at the moment the only alternative I found is to use the parser module of the dateutil package. `parser.parse('2021-08-12T09:15:17+02:00')`, your solution works fine too – Matteo Pasini Aug 12 '21 at 07:33
  • if performance + 3rd party libs are not an issue, I'm with you, dateutil's parser is a convenient alternative. Btw. with Python 3.8, datetime.fromisoformat should do an even better job, see e.g. [this](https://stackoverflow.com/a/61710371/10197418) ;-) – FObersteiner Aug 12 '21 at 07:46

0 Answers0