faqts : Computers : Programming : Languages : Python : Common Problems : Date / Time

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

9 of 10 people (90%) answered Yes
Recently 6 of 7 people (86%) answered Yes

Entry

Is there a quick way to see if a string is a valid date?

Jun 25th, 2000 20:30
unknown unknown, richard_chamberlain


Marc Lemburg's mxDateTime module (do a search at www.vex.net/parnassus)
returns a RangeError if you create a date that doesn't exist. I've 
created a checkDate method below which returns 0 or 1.

mxDateTime is an excellent module if you're going to be doing anything
complicated with dates or times.

import DateTime

def checkDate(y,m,d):
    "year,month,day"
    try:
        checkDate=DateTime.DateTime(y,m,d)
    except DateTime.RangeError:
        return 0
    else:
        return 1
def testDates(y,m,d):
    print '%d/%d/%d' %(y,m,d)
    if checkDate(y,m,d):
        print 'is ok'
    else:
        print 'is not valid'

def main():
    testDates(2000,3,10)
    testDates(2000,13,3)

if __name__=='__main__':
    main()