关于日期时间和时间的 Python 错误处理

hoo*_*ooo 0 python datetime

我有一个名为的变量pubdate,它源自 rss feed。大多数时候它是一个时间元组,这正是我想要的,所以没有错误。

有时它是一个 unicode 字符串,这就是令人烦恼的地方。

到目前为止,我有以下关于pubdate何时是 unicode 字符串的代码:

if isinstance(pubdate, unicode):
    try:
        pubdate = time.mktime(datetime.strptime(pubdate, '%d/%m/%Y %H:%M:%S').timetuple()) # turn the string into a unix timestamp
    except ValueError:
        pubdate = re.sub(r'\w+,\s*', '', pubdate) # removes day words from string, i.e 'Mon', 'Tue', etc.
        pubdate = time.mktime(datetime.strptime(pubdate, '%d %b %Y %H:%M:%S').timetuple()) # turn the string into a unix timestamp
Run Code Online (Sandbox Code Playgroud)

但我的问题是,如果 unicode 字符串的格式pubdate与子句中的格式不同,except ValueError它将引发另一个ValueError,处理多种ValueError情况的 pythonic 方法是什么?

luo*_*luo 6

当您从 Rss 解析日期字符串时。也许您在解析日期字符串时需要一些猜测。我建议您使用dateutil而不是 datetime 模块。

dateutil.parser提供通用的日期/时间字符串解析器,它能够解析大多数已知的格式来表示日期和/或时间。

该函数的原型为:(parse(timestr)不必自己指定格式)。

演示版

>>> parse("2003-09-25T10:49:41")
datetime.datetime(2003, 9, 25, 10, 49, 41)

>>> parse("2003-09-25T10:49")
datetime.datetime(2003, 9, 25, 10, 49)

>>> parse("2003-09-25T10")
datetime.datetime(2003, 9, 25, 10, 0)

>>> parse("2003-09-25")
datetime.datetime(2003, 9, 25, 0, 0)

>>> parse("Sep 03", default=DEFAULT)
datetime.datetime(2003, 9, 3, 0, 0)
Run Code Online (Sandbox Code Playgroud)

模糊解析:

>>> s = "Today is 25 of September of 2003, exactly " \
...     "at 10:49:41 with timezone -03:00."
>>> parse(s, fuzzy=True)
datetime.datetime(2003, 9, 25, 10, 49, 41,
              tzinfo=tzoffset(None, -10800))
Run Code Online (Sandbox Code Playgroud)