Python正则表达式来处理不同类型的日期

标签 python regex datetime

我正在尝试编写一个正则表达式来识别一些日期。

我正在处理的字符串是:

string:
'these are just rubbish 11-2-2222, 24-3-1695-194475 12-13-1111, 32/11/2000\
 these are dates 4-02-2011, 12/12/1990, 31-11-1690,  11 July 1990, 7 Oct 2012\
 these are actual deal- by 12 December six people died and in June 2000 he told, by 5 July 2001, he will leave.'

正则表达式看起来像:

re.findall('(\
[\b, ]\
([1-9]|0[1-9]|[12][0-9]|3[01])\
[-/.\s+]\
(1[1-2]|0[1-9]|[1-9]|Jan|January|Feb|February|Mar|March|Apr|April|May|Jun|June|Jul|July|Aug|August|Sept|September|Oct|October|Nov|November|Dec|December)\
(?:[-/.\s+](1[0-9]\d\d|20[0-2][0-5]))?\
[^\da-zA-Z])',String)

我得到的输出是:

[(' 11-2-', '11', '2', ''),
 (' 24-3-1695-', '24', '3', '1695'),
 (' 4-02-2011,', '4', '02', '2011'),
 (' 12/12/1990,', '12', '12', '1990'),
 (' 31-11-1690,', '31', '11', '1690'),
 (' 11 July 1990,', '11', 'July', '1990'),
 (' 7 Oct 2012 ', '7', 'Oct', '2012'),
 (' 12 December ', '12', 'December', ''),
 (' 5 July 2001,', '5', 'July', '2001')]

问题:

  1. 前两个输出是错误的,它们是因为可选表达式 ((?:[-/.\s+](1[0-9]\d\d|20[0- 2][0-5]))?) 用来处理像 "12 December" 这样的情况。我该如何摆脱它们?

  2. 表达式未处理一个案例 “2000 年 6 月”
    我可以用表达式实现一些东西来处理这种情况而不影响其他人吗?

最佳答案

我会避免尝试使用正则表达式来解析您的日期。正如您所发现的,它开始时没问题,但很快就会变得更难捕捉边缘情况,例如无效日期,例如2018/09/31

更安全的方法是让 Python 的 datetime 决定日期是否有效。然后您可以轻松指定有效的日期范围和允许的日期格式。

此脚本通过使用正则表达式来提取所有单词和数字组。然后它一次包含三个部分并应用允许的日期格式。如果 datetime 成功解析给定格式,则会对其进行测试以确保它在您允许的日期范围内。如果有效,则跳过匹配部分以避免在部分日期进行第二次匹配。

如果找到的日期不包含年份,则假定为 default_year:

from itertools import tee
from datetime import datetime
import re


valid_from = datetime(1920, 1, 1)
valid_to = datetime(2030, 1, 1)
default_year = 2018

dt_formats = [
    ['%d', '%m', '%Y'], 
    ['%d', '%b', '%Y'],
    ['%d', '%B', '%Y'],
    ['%d', '%b'],
    ['%d', '%B'],
    ['%b', '%d'],
    ['%B', '%d'],
    ['%b', '%Y'],
    ['%B', '%Y'],
]

text = """these are just rubbish 11-2-2222, 24-3-1695-194475 12-13-1111, 32/11/2000
these are dates 4-02-2011, 12/12/1990, 31-11-1690,  11 July 1990, 7 Oct 2012
these are actual deal- by 12 December six people died and in June 2000 he told, by 5 July 2001, he will leave."""

t1, t2, t3 = tee(re.findall(r'\b\w+\b', text), 3)
next(t2, None)
next(t3, None)
next(t3, None)
triples = zip(t1, t2, t3)

for triple in triples:
    for dt_format in dt_formats:
        try:
            dt = datetime.strptime(' '.join(triple[:len(dt_format)]), ' '.join(dt_format))

            if '%Y' not in dt_format:
                dt = dt.replace(year=default_year)

            if valid_from <= dt <= valid_to:
                print(dt.strftime('%d-%m-%Y'))

                for skip in range(1, len(dt_format)):
                    next(triples)
            break

        except ValueError:
            pass

对于您提供的文本,这将显示:

04-02-2011
12-12-1990
11-07-1990
07-10-2012
12-12-2018
01-06-2000
05-07-2001

关于Python正则表达式来处理不同类型的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33145399/

相关文章:

c# - 在 Regex C# 中允许撇号、点、符号、数字和字符

python - 如何将 RFC 2822 日期/时间解析为 Python 日期时间?

Python IRC 客户端 : write from scratch or write plugin for existing framework?

python - 如何用正则表达式同时搜索两个可能的引号?

python - Pycharm无法安装TensorFlow

javascript - 如何将数组中的值添加到对象?

c# - 如果输入为空,如何转换为 DateTime 但具有默认值?

python - 如何使用 timedelta64 添加小数天数?

python - Sympy - 从三角方程中得到两个解,我原本期望只有一个

python - Pytables 检查列是否存在