3

有谁知道如何使用 Python 的 strptime 方法解析标题中描述的格式?

我有类似的东西:

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

我似乎无法弄清楚这是哪种时间格式。顺便说一句,我是 Python 语言的新手(我习惯于 C#)。

更新

这就是我根据以下建议(答案)更改代码的方式:

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

4 回答 4

5

该日期采用 ISO 8601,或更具体地说是RFC 3339格式。

这样的日期不能用strptime. 有一个Python 问题讨论了这一点。

dateutil.parser.parse可以处理各种各样的日期,包括您示例中的日期。

如果您使用外部模块进行 XML 或 RSS 解析,则其中可能有一个例程来解析该日期。

于 2010-10-15T23:09:33.630 回答
0

这是找到答案的好方法:使用strftime, 构造一个格式字符串,该字符串将发出您所看到的内容。根据定义,该字符串将是解析时间所需的字符串strptime

于 2010-10-15T22:51:46.430 回答
0

如果您尝试解析 RSS 或 Atom 提要,请使用Universal Feed Parser。它支持许多日期/时间格式

>>> 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)
于 2010-10-16T08:28:46.217 回答
-1

这是标准的 XML 日期时间格式,ISO 8601。如果您已经在使用 XML 库,那么它们中的大多数都内置了日期时间解析器。xml.utils.iso8601工作得相当好。

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

您可以在这里查看许多其他处理方法: http ://wiki.python.org/moin/WorkingWithTime

于 2010-10-15T22:49:35.017 回答