python中正则表达式匹配年份_使用python正则表达式匹配日期

您可以使用datetime模块来解析日期:

import datetime

print datetime.datetime.strptime('2010-08-27', '%Y-%m-%d')

print datetime.datetime.strptime('2010-15-27', '%Y-%m-%d')

输出:

2010-08-27 00:00:00

Traceback (most recent call last):

File "./x.py", line 6, in

print datetime.datetime.strptime('2010-15-27', '%Y-%m-%d')

File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime

(data_string, format))

ValueError: time data '2010-15-27' does not match format '%Y-%m-%d'

因此捕获ValueError会告诉您日期是否匹配:

def valid_date(datestring):

try:

datetime.datetime.strptime(datestring, '%Y-%m-%d')

return True

except ValueError:

return False

要允许各种格式,您可以测试所有可能性,或者使用re首先解析字段:

import datetime

import re

def valid_date(datestring):

try:

mat=re.match('(\d{2})[/.-](\d{2})[/.-](\d{4})$', datestring)

if mat is not None:

datetime.datetime(*(map(int, mat.groups()[-1::-1])))

return True

except ValueError:

pass

return False


版权声明:本文为weixin_42412396原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。