简体   繁体   中英

How to convert JS date string into django datetime format?

I have a Bootstrap datepicker and on date selection, I make an ajax call and send in the user selected date, I want to change the date of the object in the database, but I get this error from Django:

[u"'04/23/2018' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]

How do I convert it to the specified format? This is my code:

Template:

$('#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()

You can use a third party library like 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
import datetime

project.end_date = datetime.datetime.strptime(request.GET.get('new_date'), '%m/%d/%Y').strftime('%Y-%m-%d')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM