views:

1232

answers:

4

I'm getting a datetime string in a format like "2009-05-28T16:15:00" (this is ISO 8601, I believe) one hack-ish option seems to be to parse the string using time.strptime and passing the first 6 elements of the touple into the datetime constructor, like:

datetime.datetime(*time.strptime("2007-03-04T21:08:12", "%Y-%m-%dT%H:%M:%S")[:6])

I haven't been able to find a "cleaner" way of doing this, is there one?

+9  A: 

With Pyhon 2.5:

datetime.datetime.strptime( "2007-03-04T21:08:12", "%Y-%m-%dT%H:%M:%S" )
Bluebird75
How in high hell did I miss that? Thanks a ton!
Andrey Fedorov
Perhaps you were looking the datetime module level functions, instead of the datetime.datetime class methods.
ΤΖΩΤΖΙΟΥ
You gotta agree though that this contradicts python ideology, being rather unobvious... `strptime`? Couldn't they use a meaningful name rather than propagate an old crappy C name?...
romkyns
Maybe I'm missing something, but I don't think this would successfully parse a valid ISO-8601 datetime which included time zone information. In that case the string would end with either an offset such as `-06:00` or with `Z` for UTC, and `strptime` would throw an exception.
Avi Flax
+3  A: 

I haven't tried it yet, but pyiso8601 promises to support this.

Avi Flax
A: 

I prefer using the dateutil library for it's timezone handling and generally solid date parsing. If you were to get an ISO 8601 string like: 2010-05-08T23:41:54.000Z you'd have a fun time parsing that with strptime, especially if you didn't know up front whether or not the timezone was included. pyiso8601 has a couple of issues (check their tracker) that I ran in to during my usage and it hasn't been updated in a few years. dateutil, by contrast, has been active and worked for me:

import dateutil.parser
yourdate = dateutil.parser.parse(datestring)
Wes Winham
A: 

Isodate seems to have the most complete support.

Tobu