使用正则表达式匹配字符,得到有效日期格式
在处理Excel表格时会遇到提取日期的情况,但人工会输入有误,然后出现各种各样的格式,这时就需要使用Python强大的正则表达式实现目标了。
- 拿一个列表List举例,把列表
a
中的字符变成yyyymmdd
格式放进列表b
我们通过使用正则表达式从每个字符串中取出对应年月日的数字
通过datetime进行转换得到需要的日期
详细代码如下 :
import re
from datetime import datetime, date, timedelta
a = ['7/6', '7/26', '12/6', '12/26', '76', '726', '126', '1226',
'7/6/2022', '7/26/2022', '12/6/2022', '12/26/2022',
'7/6/22', '7/26/22', '12/6/22', '12/26/22']
b = []
for i in a:
m = re.match(r'^(\d{1,2}?)\D?(\d{1,2})$', i)
n = re.match(r'^(\d{1,2}?)\D?(\d{1,2})\D?(\d{1,4})$', i)
if m:
mon = m.group(1)
day = m.group(2)
year = datetime.today().year # 76(7/6), 726(7/26), 126(1/26), 1226(12/26)
ymd = f"{year}/{mon}/{day}"
date = datetime.strptime(ymd, '%Y/%m/%d').strftime('%Y%m%d')
b.append(date)
elif n:
mon = n.group(1)
day = n.group(2)
if len(n.group(3))==4:
year = n.group(3) # 7/6/2022, 7/26/2022, 12/6/2022, 12/26/2022
elif len(n.group(3))==2:
year = "20" + n.group(3) # 7/6/22, 7/26/22, 12/6/22, 12/26/22
ymd = f"{year}/{mon}/{day}"
date = datetime.strptime(ymd, '%Y/%m/%d').strftime('%Y%m%d')
b.append(date)
display(a, b)
输出结果
['7/6',
'7/26',
'12/6',
'12/26',
'76',
'726',
'126',
'1226',
'7/6/2022',
'7/26/2022',
'12/6/2022',
'12/26/2022',
'7/6/22',
'7/26/22',
'12/6/22',
'12/26/22']
['20220706',
'20220726',
'20221206',
'20221226',
'20220706',
'20220726',
'20220126',
'20221226',
'20220706',
'20220726',
'20221206',
'20221226',
'20220706',
'20220726',
'20221206',
'20221226']