Python正则表达式匹配日期 [英] Python regex to match dates
问题描述
我在Python中使用什么正则表达式来匹配这样的日期: 11/12/98?
What regular expression in Python do I use to match dates like this: "11/12/98"?
推荐答案
代替使用正则表达式,通常最好将字符串解析为 datetime.datetime
对象:
Instead of using regex, it is generally better to parse the string as a datetime.datetime
object:
In [140]: datetime.datetime.strptime("11/12/98","%m/%d/%y")
Out[140]: datetime.datetime(1998, 11, 12, 0, 0)
In [141]: datetime.datetime.strptime("11/12/98","%d/%m/%y")
Out[141]: datetime.datetime(1998, 12, 11, 0, 0)
然后,您可以将日期,月份和年份(以及小时,分钟和秒)作为 datetime.datetime
对象的属性来访问:
You could then access the day, month, and year (and hour, minutes, and seconds) as attributes of the datetime.datetime
object:
In [143]: date.year
Out[143]: 1998
In [144]: date.month
Out[144]: 11
In [145]: date.day
Out[145]: 12
要测试以斜杠分隔的数字序列是否表示有效日期,可以使用 try..except
块。无效的日期将引发 ValueError
:
To test if a sequence of digits separated by forward-slashes represents a valid date, you could use a try..except
block. Invalid dates will raise a ValueError
:
In [159]: try:
.....: datetime.datetime.strptime("99/99/99","%m/%d/%y")
.....: except ValueError as err:
.....: print(err)
.....:
.....:
time data '99/99/99' does not match format '%m/%d/%y'
如果您需要搜索更长的字符串以获取日期,则可以使用
使用正则表达式来搜索以正斜杠分隔的数字:
If you need to search a longer string for a date, you could use regex to search for digits separated by forward-slashes:
In [146]: import re
In [152]: match = re.search(r'(\d+/\d+/\d+)','The date is 11/12/98')
In [153]: match.group(1)
Out[153]: '11/12/98'
当然,无效日期也将匹配:
Of course, invalid dates will also match:
In [154]: match = re.search(r'(\d+/\d+/\d+)','The date is 99/99/99')
In [155]: match.group(1)
Out[155]: '99/99/99'
要检查 match.group(1 )
返回有效的日期字符串,然后可以使用 datetime.datetime.strptime
进行解析,如上所示。
To check that match.group(1)
returns a valid date string, you could then parsing it using datetime.datetime.strptime
as shown above.
这篇关于Python正则表达式匹配日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!