python 正则表达式获取字符串中所有的日期和时间

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43886133/article/details/102763892

提取日期前的处理

  1. 处理文本数据的日期格式统一化
text = "2015年8月31日,衢州元立金属制品有限公司仓储公司(以下简称元立仓储公司)成品仓库发生一起物体打击事故,造成直接经济损失95万元。"
text1 = "2015/12/28下达行政处罚决定书"
text2 = "2015年8月发生一起物体打击事故"
# 对文本处理一下 # 2015-8-31   2015-12-28
text = text.replace("年", "-").replace("月", "-").replace("日", " ").replace("/", "-").strip()
  1. 提取时间的正则表达式
# 2019年10月27日 9:46:21
"(\d{4}-\d{1,2}-\d{1,2} \d{1,2}:\d{1,2}:\d{1,2})"
# 2019年10月27日 9:46"
"(\d{4}-\d{1,2}-\d{1,2})"
# 2019年10月27日
"(\d{4}-\d{1,2}-\d{1,2})"
# 2019年10月
"(\d{4}-\d{1,2})"
  1. 对其进行封装
def get_strtime(text):
	text = text.replace("年", "-").replace("月", "-").replace("日", " ").replace("/", "-").strip()
	text = re.sub("\s+", " ", text)
	t = ""
	regex_list = [
		# 2013年8月15日 22:46:21
        "(\d{4}-\d{1,2}-\d{1,2} \d{1,2}:\d{1,2}:\d{1,2})",
        # "2013年8月15日 22:46"
        "(\d{4}-\d{1,2}-\d{1,2} \d{1,2}:\d{1,2})",
        # "2014年5月11日"
        "(\d{4}-\d{1,2}-\d{1,2})",
        # "2014年5月"
        "(\d{4}-\d{1,2})",
	]
	for regex in regex_list:
		t =  re.search(regex, text)
		if t:
			t = t.group(1)
			return t
	else:
		print("没有获取到有效日期")
	
	return t

猜你喜欢

转载自blog.csdn.net/weixin_43886133/article/details/102763892
今日推荐