Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding out if its a leap year and setting accordingly

I have a form that has an initial end_date. I am having a Value error because this year is a leap year and we are currently in February.

My code has a end day of 30 but I am having trouble figuring out how to write the code that will discover if its a leap year and set the initial end_date to the correct last day of february.

Here is my forms.py that controls the end_date initial value

class MaturityLetterSetupForm(forms.Form):
def __init__(self, *args, **kwargs):
    from datetime import datetime
    today = datetime.today()
    start_year = today.year
    start_month = today.month
    start_date = datetime(start_year, start_month, 1)
    try:
        end_date = datetime(start_year, start_month, 30)
    except ValueError:
        end_date = datetime(start_year, start_month, ?)

    super(MaturityLetterSetupForm, self).__init__(*args, **kwargs)
    self.fields['start_date'] = forms.DateField(initial=start_date.strftime("%B %d, %Y"),
        widget=forms.TextInput(attrs={'class':'datepicker', 'value': today }))

    self.fields['end_date'] = forms.DateField(initial=end_date.strftime("%B %d, %Y"),
        widget=forms.TextInput(attrs={'class':'datepicker', 'value': today }))

EDIT After speaking to @Paul my init became:

def __init__(self, *args, **kwargs):
    from datetime import datetime
    import calendar
    today = datetime.today()
    start_year = today.year
    start_month = today.month
    start_date = datetime(start_year, start_month, 1)
    if calendar.isleap(start_year) and today.month == 2:
        end_date = datetime(start_year, start_month, calendar.mdays[today.month]+1)
    else:
        end_date = datetime(start_year, start_month, calendar.mdays[today.month])
    super(MaturityLetterSetupForm, self).__init__(*args, **kwargs)
    self.fields['start_date'] = forms.DateField(initial=start_date.strftime("%B %d, %Y"),
        widget=forms.TextInput(attrs={'class':'datepicker', 'value': today }))

    self.fields['end_date'] = forms.DateField(initial=end_date.strftime("%B %d, %Y"),
        widget=forms.TextInput(attrs={'class':'datepicker', 'value': today }))

Which finds the last day of the current month.

like image 695
TheLifeOfSteve Avatar asked Feb 03 '12 15:02

TheLifeOfSteve


1 Answers

How about calendar.isleap(year) ?

Also, don't use try/except to handle this but an if conditional. Something like:

if calendar.isleap(year):
    do_stuff
else:
   do_other_stuff
like image 107
Paul Sasik Avatar answered Oct 05 '22 01:10

Paul Sasik