我有一个 daterangepicker,用户可以从中设置日期。格式的选择是“DD MMM YYYY”现在我正在使用
datetime.datetime.strptime(time, "%d %b %Y");
但我仍然遇到错误
Exception Value:[u"'01 Aug 2013' value has an invalid date format. It must be in YYYY-MM-DD format."]
知道可能出了什么问题吗?坚持了一段时间。
def form_valid(self, form):
new_obj = form.save(commit=False)
new_obj.date_pickup_from, new_obj.date_pickup_to = form.cleaned_data['pickup_daterange'].split(' to ')
new_obj.date_delivery_from, new_obj.date_delivery_to = form.cleaned_data['delivery_daterange'].split(' to ')
这是表格
pickup_daterange = forms.CharField(
label=_('Pickup Within'),
widget=forms.TextInput(attrs={'class': 'daterange'}),
validators=[
RegexValidator(
regex=r'\d{2}\ \w{3}\ \d{4}\ to\ \d{2}\ \w{3}\ \d{4}',
message=_(u'Range must be of format "mm/dd/yyyy to mm/dd/yyyy"'),
code='invalid_range'
)
],
help_text=_('Within what dates do you want the pickup?')
)
delivery_daterange = forms.CharField(
label=_('Delivery Within'),
widget=forms.TextInput(attrs={'class': 'daterange'}),
validators=[
RegexValidator(
regex=r'\d{2}\ \w{3}\ \d{4}\ to\ \d{2}\ \w{3}\ \d{4}',
message=_(u'Range must be of format "mm/dd/yyyy to mm/dd/yyyy"'),
code='invalid_range'
)
],
help_text=_('Within what dates do you want the delivery?')
)
模型.py
date_delivery_from = models.DateField(_('Date of Delivery From'), blank=True, null=True)
date_delivery_to = models.DateField(_('Date of Delivery To'), blank=True, null=True)
在我调用 strptime 的表单类中的函数
def clean_delivery_daterange(self):
daterange_pattern = re.compile(r'(\d{2}\ \w{3}\ \d{4})\ to\ (\d{2}\ \w{3}\ \d{4})')
delivery_daterange = self.cleaned_data['delivery_daterange']
pickup_daterange = self.cleaned_data['pickup_daterange']
str_pickup_from, str_pickup_to = daterange_pattern.search(pickup_daterange).groups()
str_delivery_from, str_delivery_to = daterange_pattern.search(delivery_daterange).groups()
delivery_from = datetime.datetime.strptime(str_delivery_from, "%d %b %Y")
pickup_from = datetime.datetime.strptime(str_pickup_from, "%d %b %Y")
if delivery_from < pickup_from:
raise forms.ValidationError('Delivery dates cannot be before pickup dates')
return delivery_daterange