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

2025-05-29 0 69

提取日期前的处理

1.处理文本数据的日期格式统一化

?

1

2

3

4

5
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.提取时间正则表达式

?

1

2

3

4

5

6

7

8
# 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.对其进行封装

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23
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提取字符串日期

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35
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 正则表达式获取字符串中所有的日期时间,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对快网idc网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 python 正则表达式获取字符串中所有的日期和时间 https://www.kuaiidc.com/88490.html

相关文章

发表评论
暂无评论