首页 > 解决方案 > 日期时间收到一个天真的日期时间,而我在时区之前精确

问题描述

我正在做一个 Django 项目。这是我的代码:

today = datetime.datetime.now()
currentperiod = Day.objects.get(enddate__gte=today.date(),
                                               startdate__lte=today.date())

我收到了这条信息:

RuntimeWarning: DateTimeField Day.startdate received a naive datetime (2021-10-04 00:00:00) while time zone support is active.
  warnings.warn("DateTimeField %s.%s received a naive datetime "

所以我尝试了:

today = datetime.datetime.now()
today = pytz.timezone("Europe/Paris").localize(today, is_dst=None)
            currentperiod = Period.objects.get(enddate__gte=today.date(),
                                               startdate__lte=today.date())

但是当我使用pytz时它不起作用,我想它来自today.date()但我不知道如何进一步进行......

请问你能帮帮我吗 ?

非常感谢 !

标签: pythondjangodatetimepython-datetime

解决方案


Adate没有时区信息,因此本地化不起作用。您可以做的是截断今天,然后将其添加为过滤:

today = datetime.datetime.now()
today = pytz.timezone("Europe/Paris").localize(today, is_dst=None)
today = today.replace(hour=0, minute=0, second=0, microsecond=0)

currentperiod = Period.objects.get(
    startdate__lte=today,
    enddate__gte=today
)

如果您想在一天结束enddate前检查,那么您可以使用:

from datetime import timedelta

today = datetime.datetime.now()
today = pytz.timezone("Europe/Paris").localize(today, is_dst=None)
today = today.replace(hour=0, minute=0, second=0, microsecond=0)

currentperiod = Period.objects.get(
    startdate__lte=today,
    enddate__gte=today + timedelta(days=1, microseconds=-1)
)

推荐阅读