Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
768 views
in Technique[技术] by (71.8m points)

regex - match dates using python regular expressions

I want to match dates that have the following format:

2010-08-27, 2010/08/27

Right now I am not very particular about the date being actually feasible, but just that it is in the correct format.

please tell the regular expression for this.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the datetime module to parse dates:

import datetime

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

output:

2010-08-27 00:00:00
Traceback (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'

So catching ValueError will tell you if the date matches:

def valid_date(datestring):
    try:
        datetime.datetime.strptime(datestring, '%Y-%m-%d')
        return True
    except ValueError:
        return False

To allow for various formats you could either test for all possibilities, or use re to parse out the fields first:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...