今天分享一個Python正則表達式匹配日期與時間的方法,因為最近在做的項目需要從字符串里面把日期時間提取出來。
不多說,直接上代碼:
import re from datetime import datetime #python正則表達式匹配中文日期時間 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= """ 平安夜聖誕節2016-12-24的日子與去年2015/12/24的是有不同哦. """ # 根據正則查找所有日期並返回 matches_list=date_reg_exp.findall(test_str) # 列出並打印匹配的日期 for match in matches_list: print match # 2016-12-24 # 2015/12/24
本文主要介紹了Python的時間精確規則匹配方法,並對Python的時間格式規則匹配技術進行了比較和分析,供有需要的朋友參考。用正則表達式精確匹配時間並不容易。
我的其他文章: