So I have this Post
model. I want to be able to retrieve all posts that were created
in a month, year under a certain time zone.
My goal is to implement a feature where a user anywhere in the world let's say in PST can get all posts by another person from a certain month in their time zone. So let's say user A is in EST and user B is in PST (3 hours behind EST). User B wants to see all posts that user A created in October of 2021. Since the app will display posts in the time zone the user is currently in (we send date time in UTC then the front-end converts to local time) then the app should only send to user B all posts by user A that were created in October 2021 PST. So for example if user A (the user in EST) made a post at 11pm Oct 31 2021 EST(8pm Oct 31 2021 PST) and a post at 1am Nov 1st 2021 EST (10pm Oct 31st 2021 PST) then user B should on get both posts back, because the 2nd one was made in November in EST, but October in PST.
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)
So for example if a user creates 10 posts in November, 2 in December of 2021 in PST. Then I have a view that takes month
, year
and time_zone
and let's say the url looks something like /post/<int:month>/<int:year>/<str:time_zone>
and the user pings /post/11/2021/PST
then it should return the 10 posts from November. How do I return all posts from a month and year in a time zone given time zone, month and year?
Note: The tricky edge case to take into consideration is if they post on the very last day of a month very late. Depending on the time zone something like 12/31/2021 in UTC could be 01/01/2022. Because Django stores datetime
fields in UTC what would need to be done is converted created
to the given time_zone
then get posts from the specified month
and year
.
Setup:
- Django 3.2.9
- Postgresql
Attempted Solutions
- The most obvious solution to me is to convert
created
to the specifiedtime_zone
then to doPost.objects.filter(created__in_range=<some range>)
Note
Main issue seems to be Pyzt, which takes in time in a very specific format "Amercian/Los_Angeles" w.e format this is. Rather than the abbreviated time zone format like "PST".
from Django - Given time zone, month and year get all post created on that date in that time zone
No comments:
Post a Comment