Convert string with UTC offset to datetime object

Given this line: "Fri, 09 Apr 2010 14:10:50 +0000" how to convert it to a datetime object?

After some reading, I feel that this should work, but this is not ...

 >>> from datetime import datetime >>> >>> str = 'Fri, 09 Apr 2010 14:10:50 +0000' >>> fmt = '%a, %d %b %Y %H:%M:%S %z' >>> datetime.strptime(str, fmt) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.6/_strptime.py", line 317, in _strptime (bad_directive, format)) ValueError: 'z' is a bad directive in format '%a, %d %b %Y %H:%M:%S %z' 

It should be noted that this works without problems:

 >>> from datetime import datetime >>> >>> str = 'Fri, 09 Apr 2010 14:10:50' >>> fmt = '%a, %d %b %Y %H:%M:%S' >>> datetime.strptime(str, fmt) datetime.datetime(2010, 4, 9, 14, 10, 50) 

But I am stuck with "Fri, 09 Apr 2010 14:10:50 +0000" . I would rather convert just that without changing (or slicing) it in any way.

+43
python datetime
Apr 09 '10 at 16:47
source share
1 answer

It seems that strptime does not always support %z . Python just calls the C function, and strptime does not support %z on your platform.

Note: from Python 3.2, it will always work.

+39
Apr 09 '10 at 16:57
source share



All Articles