SoFunction
Updated on 2024-11-12

Python's Unstandardized Date String Handling Classes


import re
import datetime

# ***************************************************
# *
# * Description: Non-standard date string processing.
# * Author: wangye  <pcn88 at hotmail dot com>
# *
# ***************************************************
class DateParser(object):

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

    def __cutDate(self, date, flags):
        y =
        m = if flags[1] else 1
        d = if flags[2] else 1
        return (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]:
                (True)
            else:
                (False)
        return l

    def parse(self, strdate):
        """
DESCRIPTION: Time parsing method.
Parameters: strdate The time string to be analyzed, e.g. target time type datetime(1992, 2, 3)
Can be parsed as one of the following strings:
            19920203
            199203
            1992.02.03
            1992.02
            1992-02-03
            1992-02
            920203
Return Value:
If successful
tuple (datetime, flags), where datetime indicates the legal time at which the conversion was completed.
flags are flag bits indicating the number of valid bits, e.g. 199202 actually converts the year and month, the day does not, the
However, this function will return 1 day by default, but the flags will be represented as (True, True, False), the
The first two True's mean that the year and month were converted respectively, and the last False means that the day was not converted.
If it fails
Returns None.
        """
        m = (strdate)
        flags = [False, False, False]
        if m:
            matches = list(())
            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 ((results[0], results[1], results[2]), flags)
        else:
            return None

    def convert(self, strdate, format):
        """
Description: Convert a date to the specified format.
Parameters: strdate Same as the strdate parameter of the parse method.
format Python time format identifier, same as format identifier.
Return Value:
If successful, returns a time string in the specified format.
If it fails, returns None.
        """
        date = (strdate)
        if date:
            date = date[0]
            return (date, format)
        else:
            return None

    def compare(self, strdate1, strdate2):
        """
Description: Compare two dates.
Parameters: strdate1 and strdate2 are the same as the strdate parameter of the parse method.
Return Value:
It can be one of the following values
-4 strdate1 is invalid, strdate2 is valid.
-3 strdate1 is valid, strdate2 is invalid.
-2 strdate1 and strdate2 are invalid.
            -1  strdate1 < strdate2
             0  strdate1 = strdate2
             1  strdate1 > strdate2
        """
        date1,flags1 = (strdate1)
        date2,flags2 = (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