Home > database >  How do you run a function to compare two date by month?
How do you run a function to compare two date by month?

Time:07-20

I'm trying to run a function to compare today's month with the month input by a user. The dates will be input by the user as 'YYYY-MM-DD'. This is what I have so far:

class Sneaker(models.Model):
name = models.CharField(max_length=100)
brand = models.CharField(max_length=100)
description = models.TextField(max_length=250)
date = models.DateField('release date')
price = models.IntegerField()

def worn_for_the_month(self):
    return self.worn_set.filter(date=date.today().month).count == date.month

But get the following error:

fromisoformat: argument must be str

So I tried using the following function instead with string:

def worn_for_the_month(self):
    return self.worn_set.filter(date=str(date.month)) == str(date.month)

And I get this error:

%(value)s” value has an invalid date format. It must be in YYYY-MM-DD format.

I'm not sure if I'm using the right type of function at this point. I just want to compare the month we're in with the one the user entered.

CodePudding user response:

First, I think you have to indent all the items that are after the class sneaker to put those items inside the class. And then you forgot to import models. 'from django.db import models' after you 'pip install django would work. In case it says ModuleNotFoundError on django.utils, you might want to pip install django.utils too.

CodePudding user response:

If you really want to just filter by only the month value then you can do something like this (__month):

def worn_for_the_month(self):
    return self.worn_set.filter(date__month=date.today().month).count()

However, I imagine you don't really want to do this because you will count those that were worn in July 2022 as well as July 2021, 2020, and so on... Instead you can use either replace() or timedelta from the datetime library:

from datetime import datetime

""" replace the days to get the first of the month: """
today = datetime.now()
first_of_the_month = today.replace(day=1)
# output: datetime.datetime(2022, 7, 1, 19, 54, 45, 95533)

""" use timedelta to get 31 days ago: """
one_month_ago = today - timedelta(days=31)
# output: datetime.datetime(2022, 6, 18, 19, 56, 15, 39065)
  • Related