Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling leap years in Python

I have a program where the user enters a date and then compares it to another date to see which one comes first.

How would I go about writing a code where the user inputs Feb 29 and the program returns Feb 28 instead (since there is no leap year)?

Example:

def date(prompt):
''' returns the date that user inputs and validates it'''  
while True:
    try:
        date = raw_input(prompt)
        if len(date) >= 5:
            month = date[0:2]
            day = date[3:5]
        dateObject = datetime.date(2011, int(month), int(day))
        return dateObject
    except ValueError:
            print "Please enter a valid month and day"
like image 280
python1 Avatar asked Mar 15 '11 23:03

python1


1 Answers

How do you compare dates? If you use the datetime functions then this should already account for this sort of stuff.

>>> datetime.datetime(2011, 2, 28)
datetime.datetime(2011, 2, 28, 0, 0)

>>> datetime.datetime(2011, 2, 29)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: day is out of range for month

>>> datetime.datetime(1600, 2, 29)
datetime.datetime(1600, 2, 29, 0, 0)

datetime.timedelta() is used to represent the difference between two dates

>>> datetime.datetime(2011, 2, 28) + datetime.timedelta(days=10)
datetime.datetime(2011, 3, 10, 0, 0)

>>> datetime.datetime(1600, 2, 28) + datetime.timedelta(days=10)
datetime.datetime(1600, 3, 9, 0, 0)

>>> datetime.datetime(2011, 2, 28) - datetime.datetime(2011, 4, 10)
datetime.timedelta(-41)

Don't know how this fits in your code, but it may be an option ;-)

like image 141
Martin Tournoij Avatar answered Oct 09 '22 16:10

Martin Tournoij