我有一个Bootstrap datepicker并且在日期选择上,我进行了ajax调用并在用户选择的日期发送,我想更改数据库中对象的日期,但是我从Django得到了这个错误:
[u"'04/23/2018' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]
如何将其转换为指定的格式?这是我的代码:
模板:
$('#project_date').on('changeDate',function()
{
$.ajax({
url: btn.attr("data-url"),
type: 'get',
dataType: 'json',
data: {
new_date: $('#project_date_input').val()
},
success: function(data){
//do something
}
views.py
def project_change_date(request, pk):
data = dict()
project = get_object_or_404(Project, pk=pk)
project.end_date = request.GET.get('new_date')
opp.save()
答案 0 :(得分:2)
您可以使用第三方库,例如dateutil
In [14]: from dateutil.parser import parse
In [15]: c = "04/23/2018"
In [16]: parse(c)
Out[16]: datetime.datetime(2018, 4, 23, 0, 0)
In [17]: print(parse(c))
2018-04-23 00:00:00 # this format is same as your db's datetime format
答案 1 :(得分:1)
import datetime
project.end_date = datetime.datetime.strptime(request.GET.get('new_date'), '%m/%d/%Y').strftime('%Y-%m-%d')