views:

55

answers:

4

Does anyone know how to parse the format as described in the title using Pythons strptime method?

I have something similar to this:

import datetime    
date = datetime.datetime.strptime(entry.published.text, '%Y-%m-%dT%H:%M:%S.Z')

I can't seem to figure out what kind of timeformat this is. By the way, I'm a newbie at the Python language (I'm used to C#).

UPDATE

This is how I changed the code based on the advise (answers) below:

from dateutil.parser import *
from datetime import *
date = parse(entry.published.text)
A: 

That's the standard XML datetime format, ISO 8601. If you're already using an XML library, most of them have datetime parsers built in. xml.utils.iso8601 works reasonably well.

import xml.utils.iso8601
date = xml.utils.iso8601.parse(entry.published.text)

You can look at a bunch of other ways to deal with that here: http://wiki.python.org/moin/WorkingWithTime

Paul McMillan
"an XML library". Which one? Do you mean PyXML?
ma3
Most XML libraries include convenience functions for parsing XML datetimes. PyXML happened to be the example I included.
Paul McMillan
A: 

Here's a good way to find the answer: using strftime, construct a format string that will emit what you see. That string will, by definition, be the string needed to PARSE the time with strptime.

Charlie Martin
+2  A: 

That date is in ISO 8601, or more specifically RFC 3339, format.

These dates can't be parsed with strptime. There's a Python issue that discusses this.

dateutil.parser.parse can handle a wide variety of dates, including the one in your example.

If you're using an external module for XML or RSS parsing, there is probably a routine in there to parse that date.

intuited
A: 

If you are trying to parse RSS or Atom feeds then use Universal Feed Parser. It supports many date/time formats.

>>> import feedparser                 # parse feed
>>> d = feedparser.parse("http://stackoverflow.com/feeds/question/3946689")
>>> t = d.entries[0].published_parsed # get date of the first entry as a time tuple
>>> import datetime
>>> datetime.datetime(*t[:6])         # convert time tuple to datetime object
datetime.datetime(2010, 10, 15, 22, 46, 56)
J.F. Sebastian