datetime.strptime(‘2017-01-12T14:12:06.000-0500’,'%Y-%m-%dT%H:%M:%S.%f%Z')

mrjextreme6 picture mrjextreme6 · Jan 16, 2017 · Viewed 55.3k times · Source

I've been trying to convert this specific date format to a string in Python like so:

datetime.strptime(‘2017-01-12T14:12:06.000-0500’,'%Y-%m-%dT%H:%M:%S.%f%Z')

But it doesn't work.

What am I doing wrong?

Answer

Tagc picture Tagc · Jan 16, 2017

The error was that you used %Z instead of %z. From the documentation, you should use %z to match e.g. (empty), +0000, -0400, +1030

import datetime

result = datetime.datetime.strptime('2017-01-12T14:12:06.000-0500','%Y-%m-%dT%H:%M:%S.%f%z')

print(result)

Output

2017-01-12 14:12:06-05:00