我有一个包含两个字段的表单,一个字段获取所选日期,另一个字段获取所选时间,这是我的表单:
<input id="datepicker" class="form-control shadow-sm datepicker" name="date" type="text"
{%if meeting.pk%}
value="" data-value="{{meeting.date_time.date|date:'Y-m-d'}}"{%else%}
value="" data-value="2021-02-14"{%endif%}
required>
<div style="color: red;" class="invalid-feedback"></div>
</div>
<div class="col-6 pr-0">
<input id="input_from" class="form-control shadow-sm timepicker" type="time" {%if meeting.pk%}
data-value="{{meeting.date_time.time}}" {%else%} data-value="Date" {%endif%} name="time" required>
<div style="color: red;" class="invalid-feedback"></div>
</div>
我需要在表单的init函数中取出这两个字段并将它们转换为一个datetime对象并保存在模型中,这是init函数:< /p>
class CreatMeetingForm(forms.ModelForm):
date = forms.DateField(required=True)
time = forms.TimeField(required=True, widget=forms.TimeInput(format='%H:%M'))
class Meta:
model = Meeting
fields = ['time_zone','title','members_email','date','time','description','lat','lng','meeting_photo','yelp_business_id','is_virtual','meeting_url','location_name','location_address']
def __init__ (self,data=None,*args , **kwargs):
if data is not None :
data = data.copy()
date_field =data.get('date')
time_field = data.get('time')
date_time_filed = date_field+" "+time_field
date_time = datetime.strptime(date_time_filed,'%Y/%m/%d %H:%M:')
data['date_time'] = date_time
super().__init__(data,*args,**kwargs)
但我收到此错误:
ValueError at /meeting/create-meeting/
time data '2021-02-2112:30' does not match format '%Y/%m/%d %H:%M:'
Traceback Switch to copy-and-paste view
/home/admin1/envs/myvenv/lib/python3.8/site-packages/django/core/handlers/exception.py, line 47, in inner
response = get_response(request) …
▶ Local vars
/home/admin1/envs/myvenv/lib/python3.8/site-packages/django/core/handlers/base.py, line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) …
▶ Local vars
/home/admin1/envs/myvenv/lib/python3.8/site-packages/django/contrib/auth/decorators.py, line 21, in _wrapped_view
return view_func(request, *args, **kwargs) …
▶ Local vars
/home/admin1/website/meeting/views.py, line 83, in create_meeting
form = CreatMeetingForm(request.POST,request.FILES) …
▶ Local vars
/home/admin1/website/meeting/forms.py, line 46, in __init__
date_time = datetime.strptime(date_time_filed,'%Y/%m/%d %H:%M:') …
▶ Local vars
/usr/lib/python3.8/_strptime.py, line 568, in _strptime_datetime
tt, fraction, gmtoff_fraction = _strptime(data_string, format) …
▶ Local vars
/usr/lib/python3.8/_strptime.py, line 349, in _strptime
raise ValueError("time data %r does not match format %r" % …
▶ Local vars
我打印了从 data.get() 获得的日期和时间类型,它是字符串格式,这就是我尝试将其转换为日期时间的原因 有什么建议吗?
答案 0 :(得分:0)
显然 '2021-02-2112:30'
的格式字符串是 '%Y-%m-%d%H:%M'
,而不是 '%Y/%m/%d %H:%M:'
>>> spam = '2021-02-2112:30'
>>> from datetime import datetime
>>> datetime.strptime(spam, '%Y-%m-%d%H:%M')
datetime.datetime(2021, 2, 21, 12, 30)
当然,您可以决定更改字符串。