Python正则表达式匹配日期与时间的方法
下面给大家介绍下Python正则表达式匹配日期与时间
#!/usr/bin/envpython
#-*-coding:utf-8-*-
__author__='Randy'
importre
fromdatetimeimportdatetime
test_date='他的生日是2016-12-1214:34,是个可爱的小宝贝.二宝的生日是2016-12-2111:34,好可爱的.'
test_datetime='他的生日是2016-12-1214:34,是个可爱的小宝贝.二宝的生日是2016-12-2111:34,好可爱的.'
#date
mat=re.search(r"(\d{4}-\d{1,2}-\d{1,2})",test_date)
printmat.groups()
#('2016-12-12',)
printmat.group(0)
#2016-12-12
date_all=re.findall(r"(\d{4}-\d{1,2}-\d{1,2})",test_date)
foritemindate_all:
printitem
#2016-12-12
#2016-12-21
#datetime
mat=re.search(r"(\d{4}-\d{1,2}-\d{1,2}\s\d{1,2}:\d{1,2})",test_datetime)
printmat.groups()
#('2016-12-1214:34',)
printmat.group(0)
#2016-12-1214:34
date_all=re.findall(r"(\d{4}-\d{1,2}-\d{1,2}\s\d{1,2}:\d{1,2})",test_datetime)
foritemindate_all:
printitem
#2016-12-1214:34
#2016-12-2111:34
##有效时间
#如这样的日期2016-12-35也可以匹配到.测试如下.
test_err_date='如这样的日期2016-12-35也可以匹配到.测试如下.'
printre.search(r"(\d{4}-\d{1,2}-\d{1,2})",test_err_date).group(0)
#2016-12-35
#可以加个判断
defvalidate(date_text):
try:
ifdate_text!=datetime.strptime(date_text,"%Y-%m-%d").strftime('%Y-%m-%d'):
raiseValueError
returnTrue
exceptValueError:
#raiseValueError("错误是日期格式或日期,格式是年-月-日")
returnFalse
printvalidate(re.search(r"(\d{4}-\d{1,2}-\d{1,2})",test_err_date).group(0))
#false
#其他格式匹配.如2016-12-24与2016/12/24的日期格式.
date_reg_exp=re.compile('\d{4}[-/]\d{2}[-/]\d{2}')
test_str="""
平安夜圣诞节2016-12-24的日子与去年2015/12/24的是有不同哦.
"""
#根据正则查找所有日期并返回
matches_list=date_reg_exp.findall(test_str)
#列出并打印匹配的日期
formatchinmatches_list:
printmatch
#2016-12-24
#2015/12/24
https://www.pythonxyz.com/10025-python-regex-match-date-time.xyz
ps:下面看下python正则表达式中原生字符r的作用
r的作用
>>>mm="c:\\a\\b\\c"
>>>mm
'c:\\a\\b\\c'
>>>print(mm)
c:\a\b\c
>>>re.match("c:\\\\",mm).group()
'c:\\'
>>>ret=re.match("c:\\\\",mm).group()
>>>print(ret)
c:\
>>>ret=re.match("c:\\\\a",mm).group()
>>>print(ret)
c:\a
>>>ret=re.match(r"c:\\a",mm).group()
>>>print(ret)
c:\a
>>>ret=re.match(r"c:\a",mm).group()
Traceback(mostrecentcalllast):
File"",line1,in
AttributeError:'NoneType'objecthasnoattribute'group'
>>>
说明
Python中字符串前面加上r表示原生字符串
与大多数编程语言相同,正则表达式里使用"\"作为转义字符,这就可能造成反斜杠困扰。假如你需要匹配文本中的字符"\",那么使用编程语言表示的正则表达式里将需要4个反斜杠"\\":前两个和后两个分别用于在编程语言里转义成反斜杠,转换成两个反斜杠后再在正则表达式里转义成一个反斜杠。
Python里的原生字符串很好地解决了这个问题,有了原生字符串,你再也不用担心是不是漏写了反斜杠,写出来的表达式也更直观。
>>>ret=re.match(r"c:\\a",mm).group() >>>print(ret) c:\a
总结
以上所述是小编给大家介绍的Python正则表达式匹配日期与时间的方法,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!