How to convert a string into a localised date in django
Question: We are doing an AJAX call in Django, where a user enters a date and a number,
and the AJAX call looks up if there already is a document with that number and
date.

The application is internationalised and localised. The problem is how to
interpret the date sent by AJAX into a valid Python/Django date object. This
has to be done using the current users locale, ofcourse.

One solution I found does not work: [Django: how to get format date in
views?](http://stackoverflow.com/questions/8287883/django-how-to-get-format-
date-in-views)  
`get_format()` returns a string (in our case `j-n-Y`), but `strftime()`
expects a format string in the form of `%j-%n-%Y`.

Why the Django format is different from the `stftime()` format beats me, FYI
we're using Django 1.5 currently.

I think the problem is that in all examples I could find, the dates are
already date objects, and Python/Django just does formatting. What we need is
to convert the string into a date using the current locale, and THEN format
it. I was figuring this would be a standard problem, but all of the possible
solutions I found and tried don't seem to work...

Thanks,  
Erik


Answer: Submitting a ticket to Django gave me a clue to the answer. You can convert a
specific type of data into an object by passing it through the corresponding
field and calling to_python(). In my case with a date it would be like so:

    
    
    from django.forms.fields import DateField
    
    fld = DateField()
    dt = request.GET.get('date', '')
    formatted_datetime = fld.to_python(dt)
    

Erik

