您可以使用
datetime模块来解析日期:
import datetimeprint datetime.datetime.strptime('2010-08-27', '%Y-%m-%d')print datetime.datetime.strptime('2010-15-27', '%Y-%m-%d')
输出:
2010-08-27 00:00:00Traceback (most recent call last): File "./x.py", line 6, in <module> 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 datetimeimport redef 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
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)