44

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

After doing some reading I feel like this should work, but it doesn't...

>>> 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 a problem:

>>> 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'm stuck with "Fri, 09 Apr 2010 14:10:50 +0000". I would prefer to convert exactly that without changing (or slicing) it in any way.

martineau
  • 119,623
  • 25
  • 170
  • 301
Gussi
  • 553
  • 1
  • 4
  • 6
  • [`dateutil`](https://pypi.python.org/pypi/python-dateutil/)`.parser.parse` can do it in Python 2. `pip install dateutil`, and it should work from python 3.2 onwards. – n611x007 Aug 12 '15 at 15:37

1 Answers1

40

It looks as if strptime doesn't always support %z. Python appears to just call the C function, and strptime doesn't support %z on your platform.

Note: from Python 3.2 onwards it will always work.

Chris Morgan
  • 86,207
  • 24
  • 208
  • 215
clahey
  • 4,795
  • 3
  • 27
  • 20
  • 2
    Beat me to it! Check out: http://bugs.python.org/issue6641 – AlG Apr 09 '10 at 16:58
  • Thanks to both of you, I did try this with python2.5/2.6/3.1 on my win machine and python2.6/3.1 on my *nix, all yielded the same failure. I do wonder if %z actually does works for anyone, I'm guessing not. – Gussi Apr 10 '10 at 03:21
  • 3
    it is incorrect. `strptime()` is implemented in pure Python. Unlike `strftime()`; it behaves the same on all platforms. It won't work on Python 2 on any platform. – jfs Apr 09 '15 at 19:50