使用python正则表达式匹配日期 [英] match dates using python regular expressions

查看:84
本文介绍了使用python正则表达式匹配日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想匹配具有以下格式的日期:

I want to match dates that have the following format:

2010-08-27,2010/08/27

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.

请告诉正则表达式.

谢谢

推荐答案

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

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')

输出:

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'

所以捕捉 ValueError 会告诉你日期是否匹配:

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

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

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

这篇关于使用python正则表达式匹配日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆