使用本地化日期进行Django查询

3 投票
3 回答
949 浏览
提问于 2025-04-16 12:15

在我的表单里,有一个叫做 booking_date 的日期字段,它是用 AdminDateWidget 来显示的。这个 booking_date 字段的内容需要进行国际化,也就是要适应不同国家的日期格式。问题出现在我想用这个字段的值做一些操作时,比如:

booking = Booking.objects.get(booking_number='BN34D', booking_date='2010-11-21')

但是如果我的日期格式是 '%d.%m.%Y'

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

我就会遇到一个错误:'ValidationError: Enter a valid date in YYYY-MM-DD format',意思是要输入一个有效的日期,格式是 YYYY-MM-DD。

我该如何在不管使用什么日期格式的情况下进行查询呢?

3 个回答

1

根据我理解你的问题,你不确定会使用哪个地区的格式。这可能会导致一些难以解决的问题。比如“10-11-12”可能代表2012年10月11日,也可能是2010年11月12日,或者其他日期。

所以,你需要有一个有限且容易区分的日期格式集合。然后你可以这样做:

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)
4

你应该先用本地化的strftime格式来解析它。

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

strptime中使用这些格式:

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

你不应该直接让用户的输入传入查询中。

看起来你应该根据你的具体例子这样做:

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

我用这个方法解决了问题:

from django.utils import formats

formats.get_format('DATE_INPUT_FORMATS')[0]

这个格式接下来用来解析日期,就像xyld展示的那样

撰写回答