[Django]-Making Django queries with localized dates

1👍

I have solved the problem using this:

from django.utils import formats

formats.get_format('DATE_INPUT_FORMATS')[0]

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

4👍

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)

1👍

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)
👤jammon

Leave a comment