ISO to datetime object: 'z' is a bad directive

user2667326 picture user2667326 · Nov 25, 2013 · Viewed 47.3k times · Source

I am trying to convert ISO to datetime using the code below:

dt = datetime.datetime.strptime("2013-07-23T15:10:59.342107+01:00",
                                "%Y-%m-%dT%H:%M:%S.%f%z")

and I'm getting the error below:

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

What is the best way to convert an ISO string of above the format to a datetime object? I'm using Python version 2.7.6.

Answer

Max picture Max · Nov 25, 2013

Welcome to Python datetime! Dealing with dates and times is necessarily complex, and Python doesn't come fully with batteries included in this case. You can't use %z in strptime because Python has no classes to represent timezones (you are supposed to implement your own, or better yet include some other libraries).

You want to use pytz and python-dateutil. For more details see here:

Python strptime() and timezones?