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= """
     平安夜聖誕節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

 https://www.pythonxyz.com/10025-python-regex-match-date-time.xyz


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM