【问题标题】:Datetime received a naive datetime whereas I precised before the timezone日期时间收到一个天真的日期时间,而我在时区之前精确
【发布时间】:2021-11-24 23:09:22
【问题描述】:

我正在做一个 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() 但我不知道如何进一步进行......

你能帮帮我吗?

非常感谢!

【问题讨论】:

  • A date 没有时区信息。
  • enddatestartdate DateFields,还是DateTimeFields?
  • 它们是 DateTimeField
  • 你用的是什么 Django 版本?
  • 2.1.2版本

标签: python django datetime python-datetime


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2013-09-08
    • 2014-01-29
    • 1970-01-01
    • 2021-01-27
    • 2014-03-28
    • 2019-08-06
    • 2018-02-15
    • 1970-01-01
    相关资源
    最近更新 更多