下面給大家介紹下Python正則表達式匹配日期與時間
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Randy'
import re
from datetime import datetime
test_date = '他的生日是2016-12-12 14:34,是個可愛的小寶貝.二寶的生日是2016-12-21 11:34,好可愛的.'
test_datetime = '他的生日是2016-12-12 14:34,是個可愛的小寶貝.二寶的生日是2016-12-21 11:34,好可愛的.'
# date
mat = re.search(r"(\d{4}-\d{1,2}-\d{1,2})",test_date)
print mat.groups()
# ('2016-12-12',)
print mat.group(0)
# 2016-12-12
date_all = re.findall(r"(\d{4}-\d{1,2}-\d{1,2})",test_date)
for item in date_all:
print item
# 2016-12-12
# 2016-12-21
# datetime
mat = re.search(r"(\d{4}-\d{1,2}-\d{1,2}\s\d{1,2}:\d{1,2})",test_datetime)
print mat.groups()
# ('2016-12-12 14:34',)
print mat.group(0)
# 2016-12-12 14:34
date_all = re.findall(r"(\d{4}-\d{1,2}-\d{1,2}\s\d{1,2}:\d{1,2})",test_datetime)
for item in date_all:
print item
# 2016-12-12 14:34
# 2016-12-21 11:34
## 有效時間
# 如這樣的日期2016-12-35也可以匹配到.測試如下.
test_err_date = '如這樣的日期2016-12-35也可以匹配到.測試如下.'
print re.search(r"(\d{4}-\d{1,2}-\d{1,2})",test_err_date).group(0)
# 2016-12-35
# 可以加個判斷
def validate(date_text):
try:
if date_text != datetime.strptime(date_text, "%Y-%m-%d").strftime('%Y-%m-%d'):
raise ValueError
return True
except ValueError:
# raise ValueError("錯誤是日期格式或日期,格式是年-月-日")
return False
print validate(re.search(r"(\d{4}-\d{1,2}-\d{1,2})",test_err_date).group(0))
# false
# 其他格式匹配. 如2016-12-24與2016/12/24的日期格式.
date_reg_exp = re.compile('\d{4}[-/]\d{2}[-/]\d{2}')
test_str= """
平安夜圣誕節(jié)2016-12-24的日子與去年2015/12/24的是有不同哦.
"""
# 根據(jù)正則查找所有日期并返回
matches_list=date_reg_exp.findall(test_str)
# 列出并打印匹配的日期
for match in matches_list:
print match
# 2016-12-24
# 2015/12/24
?https://www.pythonxyz.com/10025-python-regex-match-date-time.xyz
? ps:下面看下python正則表達式中原生字符r的作用
?r的作用
>>> mm = "c:\\a\\b\\c"
>>> mm
'c:\\a\\b\\c'
>>> print(mm)
c:\a\b\c
>>> re.match("c:\\\\",mm).group()
'c:\\'
>>> ret = re.match("c:\\\\",mm).group()
>>> print(ret)
c:\
>>> ret = re.match("c:\\\\a",mm).group()
>>> print(ret)
c:\a
>>> ret = re.match(r"c:\\a",mm).group()
>>> print(ret)
c:\a
>>> ret = re.match(r"c:\a",mm).group()
Traceback (most recent call last):
File "
", line 1, in
AttributeError: 'NoneType' object has no attribute 'group'
>>>
說明
Python中字符串前面加上 r 表示原生字符串
與大多數(shù)編程語言相同,正則表達式里使用"\"作為轉(zhuǎn)義字符,這就可能造成反斜杠困擾。假如你需要匹配文本中的字符"\",那么使用編程語言表示的正則表達式里將需要4個反斜杠"\\":前兩個和后兩個分別用于在編程語言里轉(zhuǎn)義成反斜杠,轉(zhuǎn)換成兩個反斜杠后再在正則表達式里轉(zhuǎn)義成一個反斜杠。
Python里的原生字符串很好地解決了這個問題,有了原生字符串,你再也不用擔心是不是漏寫了反斜杠,寫出來的表達式也更直觀。
>>> ret = re.match(r"c:\\a",mm).group()
>>> print(ret)
c:\a
總結(jié)
以上所述是小編給大家介紹的Python正則表達式匹配日期與時間的方法,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復(fù)大家的!
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

