Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Get number of how many times the 25th passed by since a certain date

Hi in my django project I've got the following model and I want to make an @property function that counts how many times since the date_created there was the 25th of a month.

For Example:
I created the model on the 1.1.2019 The function should now return 3 because there were 3 25th since than.

class Plan(models.Model):
    title = models.CharField(max_length=50)
    date_created = models.DateTimeField(default=timezone.now)
    plan_type = models.IntegerField()
    owner = models.ForeignKey(User, on_delete=models.CASCADE)

Thanks for any help <3

like image 673
Janik Spies Avatar asked Oct 14 '25 03:10

Janik Spies


1 Answers

I think you should take a look at rrule function from dateutil library.

This should give you what you are looking for, but I couldn't test it yet.

from datetime import datetime
from dateutil.rrule import rrule, MONTHLY
len(list(rrule(MONTHLY, bymonthday=(25), dtstart=PlanModel.date_created, until=datetime.now())))

If you don't want to use this library, I would iterate over days looking each day number, something like this (couldn't test it neither)

from datetime import timedelta, datetime

def daterange(start_date, end_date):
    for n in range(int ((end_date - start_date).days)):
        yield start_date + timedelta(n)

start_date = PlanModel.date_created
end_date = datetime.now()

if start_date.day == 25:
    c=1
else:
    c=0

for single_date in daterange(start_date, end_date):
    if single_date.day == 25:
        c+=1
like image 98
Lu Chinke Avatar answered Oct 16 '25 17:10

Lu Chinke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!