python - 使用 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})$"
我现在已经使用了这种模式,但它不包括小时格式。如何在这种模式下同时编写日期格式和时间格式?
谢谢
解决方案
该正则表达式模式有点难以阅读,这将使其难以扩展。我可能会建议使用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
输入不符合任何这些格式的日期时都会得到一个。
推荐阅读
- angular - 类型“IGridInstanceOf”上不存在属性“选择”
' 执行 gridApi.grid.selection.selectAll 时 - android - 如何通过类名访问具有 R.id 的父元素中的元素
- abap - 在没有 NavBar 工作中心的情况下运行 Tr.launcher
- c# - 基于用户角色的不同主页
- java - 如何在 hadoop 集群中使用 tensorflow 模型运行风暴拓扑
- javascript - 使用 docker 时 Nodemon 不会重新加载
- google-chrome - 在 Chrome 中模拟会话超时/过期
- php - 如何获得 FPDF 总页数的一半?
- metatrader4 - MetaTrader 中的 ADX 计算
- swift - 来自公钥字符串的 Swift 4 中的 RSA 加密函数