Skip to content Skip to sidebar Skip to footer

Making Django Queries With Localized Dates

In my form I have a DateField called booking_date that is rendered with the AdminDateWidget. The contents of the booking_date field needs to be internationalized. The problem appea

Solution 1:

You should parse it first with a localized version of the strftime format.

from datetime import datetime
d = datetime.strptime('...')
booking.objects.get(..., booking_date=d.date())

Use these formats in strptime:

http://linux.die.net/man/3/strftime

You shouldn't rely on passing directly from the user into the query.

Looks like you should be doing the following from your specific example:

d = datetime.strptime('%d.%m.%Y')
booking = Booking.objects.get(booking_nmber='BN34D', booking_date=d)

Solution 2:

As I understand your question, you don't know for sure in advance, which locale will be used. That can bring you into unsolvable problems. ("10-11-12" could be Oct 11, 2012 or Nov 12, 2010 or ...)

So you must have a limited, distinguishable set of possible formats. Then you can do:

POSSIBLE_FORMATS = ('%d.%m.%Y', '%Y-%m-%d', '...')

for f in POSSIBLE_FORMATS:
    try:
        d = datetime.date.strptime(date_str, f)
        break
    except ValueError:
        continue
    raise ValueError

booking = Booking.objects.get(booking_number='BN34D', booking_date=d)

Solution 3:

I have solved the problem using this:

from django.utilsimport formats

formats.get_format('DATE_INPUT_FORMATS')[0]

This format is then used for parsing the date like xyld showed.

Post a Comment for "Making Django Queries With Localized Dates"