1

How to convert "Thu Jun 5 10:59:10 CDT 2014" into python datetime object?

I can't seem to get it to work due to the CDT. %Z for that is throwing errors :(

user3388884
  • 4,748
  • 9
  • 25
  • 34

2 Answers2

3

You can't use usual methods from datetime to construct the object here. As mentioned in the documentation, strptime can work only with (empty), UTC, EST, CST:

>>> datetime.datetime.strptime("Thu Jun 05 10:59:10 UTC 2014", "%a %b %d %H:%M:%S %Z %Y")
datetime.datetime(2014, 6, 5, 10, 59, 10)
>>> datetime.datetime.strptime("Thu Jun 05 10:59:10 CDT 2014", "%a %b %d %H:%M:%S %Z %Y")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data 'Thu Jun 05 10:59:10 CDT 2014' does not match format '%a %b %d %H:%M:%S %Z %Y'

You need to take a look at python-dateutil, which will parse the object into a naive datetime object (it does not take into account the timezone...):

>>> from dateutil import parser
>>> parser.parse("Thu Jun 5 10:59:10 CDT 2014")
datetime.datetime(2014, 6, 5, 10, 59, 10)
Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
  • +1 for explaining his actual issue rather than just providing some sort of workaround ... :P – Joran Beasley Jun 05 '14 at 16:12
  • I thought the timezone values listed in the doc were just examples, not an exhaustive list. I find `strptime` with a format string similar to yours (I used `%X` instead of `%H:%M:%S`) works fine with CDT (which is my timezone) and UTC (although no time conversion is performed) but fails with other timezones. – Fred Larson Jun 05 '14 at 16:20
  • @FredLarson `%X` is a shortcut for `%H:%M:%S`. Are you sure for CDT? Aren't you using `pytz`? – Maxime Lorant Jun 05 '14 at 16:25
  • I did `datetime.strptime(ds, '%a %b %d %X %Z %Y')`. Don't know anything about `pytz`. CDT, CST, UTC and GMT are all accepted. I've also tried EDT, EST, PDT, and PST. Those fail for me with the same exception you showed. – Fred Larson Jun 05 '14 at 16:33
0

dateutil can parse most date formats without effort

$ easy_install dateutil

>>> from dateutil import parser
>>> parser.parse("Thu Jun 5 10:59:10 CDT 2014")
datetime.datetime(2014, 6, 5, 10, 59, 10)

(I dont think it handles the timezone quite right though... but it certainly parses it... )

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179