我有一个初始end_date
的表单。我有一个价值错误,因为今年是闰年,我们目前是二月。
我的代码的结束日为30,但我无法弄清楚如何编写代码,以便发现它是否为闰年并将初始end_date
设置为2月的正确最后一天。
这是我控制end_date初始值的forms.py
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 }))
修改 与@Paul交谈后 我的初始化成了:
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 }))
找到当月的最后一天。
答案 0 :(得分:8)
另外,不要使用try / except来处理此问题,而应使用if
条件。类似的东西:
if calendar.isleap(year):
do_stuff
else:
do_other_stuff