Find out if it was a leap year and, accordingly,

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

My code has an end day of 30, but it's hard for me to figure out how to write a code that will open if it is a leap year, and set the start end_date to the correct last day of February.

Here is my form.py that controls the initial value of end_date

 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 talking with @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 })) 

What is the last day of the current month.

+4
source share
1 answer

What about calendar.isleap (year) ?

Also, do not use try / except to handle this, but if conditional. Sort of:

 if calendar.isleap(year): do_stuff else: do_other_stuff 
+7
source

Source: https://habr.com/ru/post/1394647/


All Articles