python - 日期时间收到一个天真的日期时间,而我在时区之前精确
问题描述
我正在做一个 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()
但我不知道如何进一步进行......
请问你能帮帮我吗 ?
非常感谢 !
解决方案
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)
)
推荐阅读
- java - 从维基百科信息框获取特定信息
- python-3.x - 两段 python 代码创建 zip 存档 两个之一被破坏
- linux - 使用 sed 替换行块
- c# - 使用 __ANDROID__ 在跨平台库中编写的代码不会在 Xamarin 表单应用程序中执行
- vue.js - b-输入模型具有字符串类型的值
- android - 构建我的 apk 时如何减小 xml 资产的大小
- arduino - ESP32 或 Arduino 上的 I2C:使用 BMP388 传感器的最大从机数量是多少
- rust - Supertrait 仅当 Self : Sized
- java - 如何将 java 文件编译为使用其他 .class 的 .class。(如果它是可能的)
- python - Keras 模型未能减少损失