程序员

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

作者:admin 2021-04-11 我要评论

提取日期前的处理 1.处理文本数据的日期格式统一化 text = "2015年8月31日,衢州元立金属制品有限公司仓储公司(以下简称元立仓储公司)成品仓库发生一起物体打...

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)

提取日期前的处理

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()

2.提取时间的正则表达式

# 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})"

3.对其进行封装

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

ps:下面看下python提取字符串中日期

import re
#删除字符串中的中文字符
def subChar(str):
  match=re.compile(u'[\u4e00-\u9fa5]')
  return match.sub('',str)
 
#提取日期
def extractDate(str):
  if not str:
    return None
  raw=subChar(str)
  if not raw:
    return None
  #提取前10位字符
  rawdate=raw[:10]
  datelist=re.findall("\d+",rawdate)
  if not datelist:
    return None
  if datelist.__len__()==3:
    if (float(datelist[0])>2099 or float(datelist[0])<1900) or float(datelist[1])>12 or float(datelist[2])>31:
      return None
    else:
      return '-'.join(datelist)
  if datelist.__len__()==2:
    if (float(datelist[0])>2099 or float(datelist[0])<1900) or float(datelist[1])>12:
      return None
    else:
      datelist.append('01')
      return '-'.join(datelist)
  if datelist.__len__()==1:
    if float(datelist[0])>20991231 or float(datelist[0])<19000101:
      return None
    else:
      return datelist[0]
  return None

总结

以上所述是小编给大家介绍的python 正则表达式获取字符串中所有的日期和时间,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对站长技术网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!


原文链接:https://m.jb51.net/article/172982.htm

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • 四两拨千斤——你不知道的VScode编码Ty

    四两拨千斤——你不知道的VScode编码Ty

  • 我是如何在 Vue 项目中做代码分割的

    我是如何在 Vue 项目中做代码分割的

  • position:sticky 粘性定位的几种巧妙应

    position:sticky 粘性定位的几种巧妙应

  • 从零到一搭建React组件库

    从零到一搭建React组件库