Python non-canonical date string processing class _python

Source: Internet
Author: User
Tags date1

I analyzed features such as 19920203, 199203, 1992.02.03, 1992.02, 1992-02-03, 1992-02, and 920203 time formats, listing the regular expressions as follows:

Copy Code code as follows:

^ ((?: 19|20)? \d{2}) [-.]? ((?: [0-1]?| 1) [0-9]) [-.]? ((?: [0-3]?| [1-3]) [0-9])? $

Of course, this expression is not very perfect, can only do simple cutting, can not determine the legality of the date, about the date is legitimate, I still give Python time to deal with it.

According to the above regular expression, I write the Dateparser class as follows:

Copy Code code as follows:

Import re
Import datetime

# ***************************************************
# *
# * Description: Non-standard date string processing
# * Author:wangye <pcn88 at hotmail Dot com>
# *
# ***************************************************
Class Dateparser (object):

def __init__ (self):
Self.pattern = Re.compile (
R ' ^ ((?: 19|20)? \d{2}) [-.]? ((?: [0-1]?| 1) [0-9]) [-.]? ((?: [0-3]?| [1-3]) [0-9])? $'
)

def __cutdate (self, date, flags):
y = date.year
m = Date.month if flags[1] Else 1
D = Date.day if flags[2] Else 1
return Datetime.date (Y, M, D)

def __mergeflags (self, FLAGS1, FLAGS2):
L = []
length = min (len (FLAGS1), Len (FLAGS2))
For I in range (0, length):
If Flags1[i] and Flags2[i]:
L.append (True)
Else
L.append (False)
return L

Def parse (self, strdate):
"""
Description: Time resolution method.
Parameters: Strdate The time string to parse, such as the target Time type DateTime (1992, 2, 3)
One of the following strings can be parsed:
19920203
199203
1992.02.03
1992.02
1992-02-03
1992-02
920203
return value:
If successful
Tuple (datetime, Flags), where DateTime represents the legal time that the conversion was completed.
Flags are flag bits, indicating the number of significant digits, such as 199202 the actual conversion of the year and month, the day did not,
However, this function returns the default of 1st, but flags will be represented as (true, true, False).
The preceding two true indicates that the year and month are converted, and the last false indicates that the day is not converted.
If you fail
Returns none.
"""
m = Self.pattern.match (strdate)
Flags = [False, False, false]
If M:
matches = List (m.groups ())
Flags = List (map (lambda x:true if x!=none else False, matches))
Results = List (map (lambda x:int (x) if x!=none else 1, matches))
# results = List (map (lambda x:1 if x==none else x, results))
If results[0]<100:
If results[0]>9:
Results[0] + + 1900
Else
Results[0] + + 2000

Return (Datetime.date (Results[0], results[1], results[2), flags)
Else
Return None

def convert (self, strdate, format):
"""
Description: The conversion date is the specified format.
Parameters: Strdate The strdate parameters of the same parse method.
Format Python time format identification, with Datetime.date.strftime format identity.
return value:
Returns a time string in the specified format format, if successful.
If it fails, returns none.
"""
Date = Self.parse (strdate)
If Date:
Date = Date[0]
return Datetime.date.strftime (date, format)
Else
Return None

def compare (self, strdate1, Strdate2):
"""
Description: Compares two dates.
Parameters: Strdate parameters of the same parse method as Strdate1 and Strdate2
return value:
Can be one of the following values
-4 strdate1 Invalid, strdate2 valid
-3 strdate1 valid, Strdate2 invalid
-2 strdate1 and Strdate2 invalid
-1 Strdate1 < Strdate2
0 strdate1 = Strdate2
1 strdate1 > Strdate2
"""
DATE1,FLAGS1 = Self.parse (strdate1)
DATE2,FLAGS2 = Self.parse (strdate2)

If date1 = = None and Date2!= None:
Return-4
If Date1!= none and Date2 = none:
Return-3
Elif Date1 = = None and Date2 = none:
Return-2

Flags = Self.__mergeflags (FLAGS1, FLAGS2)
Date1 = Self.__cutdate (date1, flags)
Date2 = Self.__cutdate (Date2, flags)

If Date1>date2:
Return 1
Elif Date1<date2:
Return-1
Else
return 0

Here are a few examples for your reference:

Copy Code code as follows:

>>> Dateparser () Parse ("19860126")
(Datetime.date (1986, 1,), [True, True, True])
>>> Dateparser () Parse ("199111")
(Datetime.date (1991, 1), [True, True, False])
>>> Dateparser () Parse ("1991")
(Datetime.date (1919, 9, 1), [True, True, True])
>>> Dateparser () Parse ("8511")
(Datetime.date (1985, 1), [True, True, False])
>>> Dateparser () convert ("19911101", "%Y *%m *%d")
' 1991 * 11 * 01 '
>>> Dateparser () convert ("1990.1.01", "%y.%m.%d")
' 1990.01.01 '
>>> dateparser (). Compare ("1992.2", "19922")
0
>>> Dateparser () compare ("1992.2", "1956.03.1")
1

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.