Leap Years Processing in Python

I have a program in which the user enters a date and then compares it with another date to see which one will be the first.

How can I write a code into which the user enters on February 29, and the program returns on February 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"
+3
source share
2 answers

How do you compare dates? If you use functions datetime, then this should already be considered by this material.

>>> 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() 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)

I don't know how this fits into your code, but it may be an option; -)

+4
source

, : month == 2 and day == 29 , calendar.isleap(). A date/datetime a ValueError, 29 -leapyear.

+2

All Articles