How to filter data from Django models using python datetime?

Submitted 4 years, 5 months ago
Ticket #275
Views 714
Language/Framework Django
Priority Low
Status Closed

How to filter data from Django models using python datetime?

Submitted on Nov 02, 20
add a comment

1 Answer

Verified

Assume Bellow model for storing messages with timelines :

class Message(models.Model):
from = models.ForeignKey(User,related_name = “%(class)s_from”)
to = models.ForeignKey(User, related_name = “%(class)s_to”)
msg = models.CharField(max_length=255)
rating = models.IntegerField(blank=’True’,default=0)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
Filter messages with specified Date and Time
today = date.today().strftime(‘%Y-%m-%d’)

yesterday = date.today() – timedelta(days=1)
yesterday = yesterday.strftime(‘%Y-%m-%d’)

this_month = date.today().strftime(‘%m’)
last_month = date.today() – timedelta(days=32)
last_month = last_month.strftime(‘%m’)
this_year = date.today().strftime(‘%Y’)

last_year = date.today() – timedelta(days=367)
last_year = last_year.strftime(‘%Y’)

today_msgs = Message.objects.filter(created_on__gte=today).count()
yesterday_msgs = Message.objects.filter(created_on__gte=yesterday).count()
this_month_msgs = Message.objects.filter(created_on__month=this_month,created_on__year=this_year).count()
last_month_msgs = Message.objects.filter(created_on__month=last_month,created_on__year=this_year).count()
this_year_msgs = Message.objects.filter(created_on__year=this_year).count()
last_year_msgs = Message.objects.filter(created_on__year=last_year).count()

Submitted 4 years, 5 months ago


Latest Blogs