所以我有这个Post
模型。我希望能够检索 created
的所有帖子某个时区下的一个月、一年。
我的目标是实现一项功能,世界上任何地方的用户(假设在太平洋标准时间)都可以获取另一个人在其时区的某个月份发布的所有帖子。假设用户 A 处于 EST,用户 B 处于 PST(比 EST 晚 3 小时)。用户 B 希望查看用户 A 在 2021 年 10 月创建的所有帖子。由于应用程序将显示用户当前所在时区的帖子(我们发送 UTC 日期时间,然后前端转换为本地时间),则应用程序应仅将用户 A 在太平洋标准时间 2021 年 10 月创建的所有帖子发送给用户 B。例如,如果用户 A(美国东部标准时间的用户)于美国东部标准时间 2021 年 10 月 31 日晚上 11 点(太平洋标准时间 2021 年 10 月 31 日晚上 8 点)发帖,并于美国东部标准时间 2021 年 11 月 1 日凌晨 1 点(太平洋标准时间 2021 年 10 月 31 日晚上 10 点)发帖,则用户 B 应该获取两个帖子都回复了,因为第二个是在美国东部时间 11 月制作的,但在太平洋标准时间是 10 月制作的。
model.py
class Post(models.Model):
uuid = models.UUIDField(primary_key=True)
created = models.DateTimeField('Created at', auto_now_add=True)
updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True)
creator = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="post_creator")
body = models.CharField(max_length=POST_MAX_LEN)
例如,如果用户在太平洋标准时间 (PST) 中于 11 月创建了 10 个帖子,在 2021 年 12 月创建了 2 个帖子。然后我有一个需要 month
的 View , year
和time_zone
假设网址类似于 /post/<int:month>/<int:year>/<str:time_zone>
用户 ping /post/11/2021/PST
那么它应该返回 11 月份的 10 个帖子。 如何返回给定时区、月份和年份的时区某一月份和一年的所有帖子?
注意:需要考虑的棘手边缘情况是,他们是否在一个月的最后一天很晚地发帖。根据时区的不同,UTC 中的 12/31/2021 可能是 01/01/2022。因为 Django 存储 datetime
UTC 字段需要进行转换 created
给定的time_zone
然后从指定的 month
获取帖子和year
.
设置:
- Django 3.2.9
- Postgresql
尝试的解决方案
- 对我来说最明显的解决方案是转换
created
到指定的time_zone
然后做Post.objects.filter(created__in_range=<some range>)
注意
主要问题似乎是 Pyzt,它以非常具体的格式“Amercian/Los_Angeles”(即这种格式)花费时间。而不是像“PST”这样的缩写时区格式。
最佳答案
Take the month's first moment (midnight on the 1st) in UTC and the next month's first moment in UTC, adjust them with the timezone you want, do a posted__range=(a, b) query?
这可能有效(但日期数学很繁琐......)。
这需要 python-dateutil
来使计算结束
时间变得稳健。
import datetime
import pytz
from dateutil.relativedelta import relativedelta
from django.utils import timezone
year = 2021
month = 6
tz = pytz.timezone("America/Los_Angeles")
start = datetime.datetime(year, month, 1)
end = start + relativedelta(months=1)
start_as_tz_in_utc = tz.localize(start).astimezone(pytz.utc)
end_as_tz_in_utc = tz.localize(end).astimezone(pytz.utc)
print(start_as_tz_in_utc, end_as_tz_in_utc, sep="\n")
打印出来
2021-06-01 07:00:00+00:00
2021-07-01 07:00:00+00:00
这似乎是正确的。
然后您可能会进行如下查询
posts = Post.objects.filter(created__range=(
start_as_tz_in_utc,
end_as_tz_in_utc,
))
关于python - Django - 给定时区、月份和年份,获取该时区该日期创建的所有帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70440712/