Method of Matching Date and Time with Python Regular Expression

  • 2021-07-10 20:20:36
  • OfStack

The following is an introduction to the matching date and time of Python regular expressions


#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Randy'
import re
from datetime import datetime
test_date = ' His birthday is 2016-12-12 14:34, It's a lovely little baby .2 Bao's birthday is 2016-12-21 11:34, It's so cute .'
test_datetime = ' His birthday is 2016-12-12 14:34, It's a lovely little baby .2 Bao's birthday is 2016-12-21 11:34, It's so cute .'
# 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
##  Effective time 
#  A date such as this 2016-12-35 It can also be matched to . The tests are as follows .
test_err_date = ' A date such as this 2016-12-35 It can also be matched to . The tests are as follows .'
print re.search(r"(\d{4}-\d{1,2}-\d{1,2})",test_err_date).group(0)
# 2016-12-35
#  You can add a judgment 
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(" Error is date format or date , The format is year - Month - Day ")
    return False
print validate(re.search(r"(\d{4}-\d{1,2}-\d{1,2})",test_err_date).group(0))
# false
#  Other format matching .  Such as 2016-12-24 And 2016/12/24 Date format of .
date_reg_exp = re.compile('\d{4}[-/]\d{2}[-/]\d{2}')
test_str= """
    Christmas Eve Christmas 2016-12-24 The days of last year 2015/12/24 There is a difference .
   """
#  Find all dates according to the regular and return 
matches_list=date_reg_exp.findall(test_str)
#  List and print matching dates 
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: Let's look at the role of the native character r in the python regular expression

Role of 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 "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
>>>

Description

The string in Python is preceded by r to denote a native string

As in most programming languages, regular expressions use "\" as the escape character, which can cause backslash trouble. If you need to match the character "\" in the text, you will need four backslashes in the regular expression expressed in the programming language: the first two and the last two are used to escape into backslashes in the programming language, convert into two backslashes and then escape into one backslash in the regular expression.

The native string in Python solves this problem well. With the native string, you don't have to worry about missing the backslash anymore, and the written expression is more intuitive.


>>> ret = re.match(r"c:\\a",mm).group()
>>> print(ret)
c:\a

Summarize

The above is the site to introduce the Python regular expression matching date and time method, I hope to help you, if you have any questions welcome to leave me a message, this site will reply to you in time!


Related articles: