문제

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)
도움이 되었습니까?

해결책

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

Such 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.

다른 팁

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.

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)

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top