使用python从复杂字符串中解析日期

时间:2013-01-27 14:21:18

标签: python string parsing date python-dateutil

我有许多字符串,其中包含不同的日期格式。我希望能够从字符串中提取日期。例如:

  • 今天是2012年8月。明天不是
  • 8月12日的另一天,又是另一次
  • 12/08是另一种格式
  • 有另一个? 08/12/12可能是
  • 终于威严12将是

我期望从这些结果得到的是2012-08-01 00:00:00,2013-08-12 00:00:00,2013-08-12 00:00:00,2012- 08-12 00:00:00,2013-08-12 00:00:00。

我目前有这段代码:

from dateutil import parser
print parser.parse("Today is August 2012. Tomorrow isn't",fuzzy=True)

您将从中看到日期打印为2012-08-27 00:00:00(因为今天是该月的第27天)。在这个例子中我想要的是2012-08-01 00:00:00。

如果没有给出一天,如何强制它始终放在月初? (例如,如果我在2012年8月给出它应该返回2012-08-01,如果我在2012年8月12日给它,它应该返回2012-08-12。)

1 个答案:

答案 0 :(得分:4)

使用default参数设置默认日期。这应该处理除第三个以外的所有情况,这有点模棱两可,可能需要一些解析器调整或一个mindreader:

In [15]: from datetime import datetime

In [16]: from dateutil import parser

In [17]: DEFAULT_DATE = datetime(2013,1,1)

In [18]: dates=["Today is August 2012. Tomorrow isn't",
    ...:        "Another day 12 August, another time",
    ...:        "12/08 is another format",
    ...:        "have another ? 08/12/12 could be", 
    ...:        "finally august 12 would be"]


In [19]: for date in dates:
    ...:     print parser.parse(date,fuzzy=True, default=DEFAULT_DATE)
    ...:     
2012-08-01 00:00:00
2013-08-12 00:00:00
2013-12-08 00:00:00  # wrong
2012-08-12 00:00:00
2013-08-12 00:00:00
相关问题