views:

688

answers:

4

I have a date string of the form '2009/05/13 19:19:30 -0400'. It seems that previous versions of python may have supported a %z format tag in strptime for the trailing timezone specification, but 2.6.x seems to have removed that.

What's the right way to parse this string into a datetime object?

A: 

Short answer is it doesn't work. Longer answer - you should see the answer for this question: python time to age part 2, timezones

geofflane
Was there some rationale given for why this was removed?
fields
I didn't see anything specific about why.
geofflane
See Guido's comment at the bottom of this page; it's from 2003 so I'm not sure if it applies to the current state of affairs: http://mail.python.org/pipermail/python-bugs-list/2003-November/021063.html
ars
That answer isn't applicable - the strftime/strptime functions in libc on the machine in question do have the %z flag, and this seems to have been explicitly removed from the 2.6.x implementation.
fields
Actually, Guidos comment there is no longer correct. Python uses, since July 2003, it's own pure python strptime. It does not and has never supported %z.
Lennart Regebro
+8  A: 

You can use the parse function from dateutil:

>>> from dateutil.parser import parse
>>> d = parse('2009/05/13 19:19:30 -0400')
>>> d
datetime.datetime(2009, 5, 13, 19, 19, 30, tzinfo=tzoffset(None, -14400))

This way you obtain a datetime object you can then use.

txwikinger
A: 

If you are on linux, then you can use the external date command to dwim :

import commands, datetime

def parsedate(text):
  output=commands.getoutput('date -d "%s" +%%s' % text )
  try:
      stamp=eval(output)
  except:
      print output
      raise
  return datetime.datetime.frometimestamp(stamp)

This is of course less portable that dateutil, but slightly more flexible, because date will also accept inputs like "yesterday" or "last year" :-)

Gyom
A: 

It's not removed. From the documentation:

"Support for the %Z directive is based on the values contained in tzname and whether daylight is true. Because of this, it is platform-specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones)."

Basically, this translates to: "Timezones is really friggin hard, and so Python doesn't do them properly out of the box".

In practice you need dateutil or pytz for any kind timezone handling in Python. (And even then there are things that are tricky: http://regebro.wordpress.com/2007/12/18/python-and-time-zones-fighting-the-beast/ )

Lennart Regebro
I was talking about %z, which are numeric values, not %Z.
fields
That wasn't removed in 2.6 either, it was "removed" in 2.3. Note that it has NEVER been documented.
Lennart Regebro