Mes*_*Qin 2 python django datetime django-timezone
我正在尝试过滤查询集以获取今年的所有帖子。
\ndef thisYearQuerySet(objects):\n start_day = datetime.date(datetime.date.today().year, 1, 1)\n end_day = datetime.date(datetime.date.today().year, 12, 31)\n return objects.filter(date__range=[start_day, end_day])\nRun Code Online (Sandbox Code Playgroud)\ndjango抱怨start_day和end_day声明可能会发生冲突django.utils.timezone,我认为这没什么大不了的。
但这个警告很烦人,任何关于忽略它的建议(而不是禁用 django 警告)将不胜感激。比如,如何获取一年中的第一天和最后一天django.utils
RuntimeWarning: DateTimeField Model.date received a naive datetime (2021-01-01 00:00:00) while time zone support is active.\nRuntimeWarning: DateTimeField Model.date received a naive datetime (2021-12-31 00:00:00) while time zone support is active.\nRun Code Online (Sandbox Code Playgroud)\n看来我必须设置一个区域来消除警告。
\n我附上了我的项目中实现的模块,其中的方法可能会对您有所帮助。
\nRuntimeWarning: DateTimeField Model.date received a naive datetime (2021-01-01 00:00:00) while time zone support is active.\nRuntimeWarning: DateTimeField Model.date received a naive datetime (2021-12-31 00:00:00) while time zone support is active.\nRun Code Online (Sandbox Code Playgroud)\ndate__根据模型日期时间字段名称进行修改,还可以根据站点的工作位置更改时区。
django抱怨start_day和end_day声明可能与django.utils.timezone冲突,我认为这没什么大不了的。
这取决于您能承受的风险程度。通过不考虑用户的时区,thisYearQuerySet可能会在临近新年时返回去年或当前年份的对象。
这是因为服务器可能在 GMT 时间运行,这意味着在 2022-01-01 00:00:00T00:00,它将开始返回包含 2022 年日期的数据。但是,任何使用该应用程序的美国人都会知道年份距 2021 年还有 4 个多小时,预计要到午夜才能看到 2021 年的数据。
但是,如果您试图消除警告并且不关心上述情况,请不要在获取今天/现在时使用 python 日期时间函数。使用:
from django.utils import timezone
now = timezone.now()
today = timezone.now().date()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3913 次 |
| 最近记录: |