通过在python中读取char来获取并验证日期

时间:2013-04-12 09:10:36

标签: python date python-2.5

如何以MM-DD-YY格式阅读日期并验证为实际日期?

  

我知道使用datetime模块处理它会更容易,更健壮 - 但这不是我想要的,所以任何使用以下代码的解决方案都表示赞赏:

  • dataType = MM-DD-YY
  • actualResult = 12-31-13
  • rIndexactualResult
  • 的计数器变量
  • rLenactualResult
  • 的长度
def compareDate (dataType, actualResult, rIndex, rLen):
    dateString =  ""
    bhCount , result , count = 0 , 0 , 0
    while (rIndex < rLen):
        ch = actualResult[rIndex]
        print ("Char %c" % ch)
        dateString += str(ch)                   
        if(ch >='0' and ch <= '9'):
            count += 1
            if(count == 2):
                count = 0
                bHyphen = False
            elif(count > 2):
                result = -1
                break
        elif(ch == "-"):            
            bhCount += 1
            if((count == 0) and (bHyphen == False)):
                bHyphen = True                
            else:
                break     
        else:
            break                       
        rIndex += 1

    #print dateString      
    return (result, rIndex)

我做错了什么?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

class ValidationError(BaseException):
    pass    

class MyDate(object):
    mounth = int()
    day = int()
    year = int()
    _correct_mounth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

    def validate(self, day, mounth, year):
        if not 1 <= mounth <= 12:
            raise ValidationError, 'Invalid mounth!'
        if year < 1:
            raise ValidationError, 'Invalid year!'
        if mounth == 2 and not year % 4:
            if not 1 <= day <= 29:
                raise ValidationError, 'Invalid day!'
        else:
            if not 1 <= day <= self._correct_mounth[mounth-1]:
                raise ValidationError, 'Invalid day!'
        return True

    def __init__(self, date):   
        if not isinstance(date, basestring):
            raise ValidationError, 'Not a string!'
        date_parts = date.split('-')
        if not isinstance(date_parts, list) or not len(date_parts) == 3:
            raise ValidationError, 'Can`t change to list with 3 elements!'
        for i in date_parts:
            try:
                int(i)
            except TypeError:
                raise ValidationError, 'Cannot convert to int!'
        mounth = int(date_parts[0])
        day = int(date_parts[1])
        year = int(date_parts[2])
        if self.validate(day, mounth, year):
            self.mounth, self.day, self.year = mounth, day, year


dates = '12-31-13|08-23-12|10-10-13'
unchecked_dates = dates.split('|')
checked_dates = list()
for d in unchecked_dates:
    try:
        new_date = MyDate(d)
    except ValidationError, e:
        print '{0} is invalid date! {1}'.format(d, e)
    else:
        checked_dates.append(new_date)
if len(unchecked_dates) == len(checked_dates):
    print 'All dates are correct.'
else:
    print 'Correct dates: {0}'.format(checked_dates)

答案 1 :(得分:1)

  

<强> ANSWER

def compareDate (dataType, actualResult, rIndex, rLen):    
    hyphenCount , result , count = 0 , 0 , 0
    dateString = ""
    while (rIndex < rLen):
        ch = actualResult[rIndex]        
        if (ch == '.'):
            break
        if(ch >= '0' and ch <= '9'):
            hyphenCount = 0
            count += 1            
            if(count > 2):
                result = -1
                print " d = "
                break;            
            dateString += str(ch)
        if(ch == '-'):
            count = 0
            hyphenCount += 1
            if(hyphenCount > 1):
                print " h = "
                result = -1
                break  

        #print ("Char %c" % ch)              
        rIndex += 1
    print "dateString is = %s" % dateString

    if result != -1:
        msg = ""         
        mt = dateString[0] + dateString[1]
        dt = dateString[2] + dateString[3]
        yr = dateString[4] + dateString[5]
        leap = '20'+yr
        print mt, dt, yr
        mt = int(mt)
        dt = int(dt)
        yr = int (yr)
        leap = int(yr)                
        #create and call function which verify date
        result,msg = verifyDate(mt,dt,yr,leap)
        print msg

    return (result, rIndex)


def verifyDate(mt,dt,yr,leap):
    res = 0
    msg = ""
    leapyr = checkForLeapYear(leap) 
    if(yr >= 00 and yr <= 99):
        if(leapyr): # for leap year
            if(mt == 2):
                if(dt >= 01 and dt <= 29):
                    res = 0
                else:
                    msg = "should not exceed 29"
            elif(mt == 1 or mt == 3 or mt == 5 or mt == 7 or mt == 8 or mt == 10 or mt == 12):
                    if(dt >= 01 and dt <= 31):
                        res = 0
                    else:
                        msg = "should not exceed 31"
                        res = -1
            elif(mt == 4 or mt == 6 or mt == 9 or mt == 11):
                    if(dt >= 01 and dt <= 30):
                        res = 0
                    else:
                        msg  = "should not exceed 30"
                        res = -1                
            else:
                    msg  = "month should in btwn 01 to 12"
                    res = -1
            # for leap year ...Ends Here

        else:                
            if((mt >= 1) and (mt <= 12)):
                if(mt == 2):
                    if(dt >= 01 and dt <= 28):
                        res = 0
                    else:
                        msg = "should not exceed 28"
                        res = -1
                elif(mt == 1 or mt == 3 or mt == 5 or mt == 7 or mt == 8 or mt == 10 or mt == 12):
                    if(dt >= 01 and dt <= 31):
                        res = 0
                    else:
                        msg = "should not exceed 31"
                        res = -1
                elif(mt == 4 or mt == 6 or mt == 9 or mt == 11):
                    if(dt >= 01 and dt <= 30):
                        res = 0
                    else:
                        msg  = "should not exceed 30"
                        res = -1                
            else:
                    msg  = "month should in btwn 01 to 12"
                    res = -1

    else:
        msg  = "year should in btwn 00 to 99"
        res = -1
    return (res,msg)   


def checkForLeapYear(yr):
    if((yr %100) == 0 and (yr % 400 == 0 )):
        return True
    elif(yr%4 == 0):
        return True
    else:
        return False
  

我还可以使用代码来提高复杂性并减少代码行。   请回答一下例子..