Erik Oosterwaal
Erik Oosterwaal

Reputation: 4374

How to convert a string into a localised date in django

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?
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

Upvotes: 2

Views: 1289

Answers (3)

Erik Oosterwaal
Erik Oosterwaal

Reputation: 4374

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

field = DateField()
value = request.GET.get('date', '')
formatted_datetime = field.to_python(value)

Erik

Upvotes: 2

YacineAzmi
YacineAzmi

Reputation: 873

If you know the format, then you should be able to use datetime.strptime .

Have used it in code successfully in conjunction with ajax calls.

See here for more information: http://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

Upvotes: 0

shx2
shx2

Reputation: 64318

Sounds to me it would make your life easier to let the user select the date from a calendar, instead of typing its string representation. This way you know exactly what you're getting.

Upvotes: 1

Related Questions