首页 > 解决方案 > 使用 Python 正则表达式匹配日期和时间

问题描述

我想匹配具有以下格式的日期和时间:

17/05/2009 8:15
17/5/2009 08:15
17.05.2009 8:15
17-05-2009 8:15
17/05/2009 8:15:00

pat = "^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$" 

我现在已经使用了这种模式,但它不包括小时格式。如何在这种模式下同时编写日期格式和时间格式?

谢谢

标签: pythonregex

解决方案


该正则表达式模式有点难以阅读,这将使其难以扩展。我可能会建议使用datetime.strptime

from datetime import datetime

dates = [
  '17/05/2009 8:15',
  '17/5/2009 08:15',
  '17.05.2009 8:15',
  '17-05-2009 8:15',
  '17/05/2009 8:15:00',
]

def parse_date(date: str) -> datetime:
    for fmt in [
        "%d/%m/%Y %H:%M",
        "%d.%m.%Y %H:%M",
        "%d-%m-%Y %H:%M",
        "%d/%m/%Y %H:%M:%S",
    ]:
        try:
            return datetime.strptime(date, fmt)
        except ValueError:
            continue
    raise ValueError(f"Couldn't parse '{date}'!")

datetimes = [parse_date(date) for date in dates]

使用这种方法,很容易添加新fmt字符串,并且很容易发现漏洞,因为您在ValueError输入不符合任何这些格式的日期时都会得到一个。


推荐阅读