Deluq Deluq - 2 months ago 8
Python Question

Jump weekends function? Django/python

I need to jump Saturday and Sunday automatically everyday so I can do a count in of certain element from a model. This is an example of the table I need to create:

Date ------- Order Holds

Today ------ 45 (wednesday)

09/09/16 --- 34 (Thursday)

10/09/16 --- 23 (Friday)

-----JUMP WEEKEND --- (and keep count in)

13/09/16 --- 56 (Monday)

14/09/16 --- 14 (Tuesday)


This is how I filter to count the number of holds for today, and I can keep getting them by adding 1 day:

This is my model(models.py):

class Reporte3a5(models.Model):
date = models.DateField(null=True, blank=True)
order holds = models.CharField(max_length=10)


This is part of my logic (views.py)

today = datetime.today()
tomorrow = today + timedelta(days=1)
orders = Report.objects.filter(date=today)
hold = orders.filter(order_holds__contains="HOLD").count()


As you can see in my views.py logic I can filter all the HOLD status from today's date, after that I can count them with now issue. My problem is that I if I filter for tomorrow and tomorrow is Friday I need to jump Saturday and Sunday. In other words, apply that logic everyday by just jumping weekends.

Answer

You can find the weekday number for a datetime by calling its weekday() method. Once you have that value you can test it to see if its one of the days you're interested in:

from datetime import datetime, timedelta

DAYS_OF_INTEREST = {0, 1, 2, 3, 4}  # Monday-Friday
DELTA_ONE_DAY = timedelta(days=1)
today = datetime.today()

day = today
for _ in range(14):  # next two weeks
    if day.weekday() in DAYS_OF_INTEREST:
        print(day.strftime(("%d/%m/%y --- %A")))
        #orders = Report.objects.filter(current_fcd_date=day)
        #hold = orders.filter(order_hold__contains="HOLD").count()
    day += DELTA_ONE_DAY

Output:

27/09/16 --- Tuesday
28/09/16 --- Wednesday
29/09/16 --- Thursday
30/09/16 --- Friday
03/10/16 --- Monday
04/10/16 --- Tuesday
05/10/16 --- Wednesday
06/10/16 --- Thursday
07/10/16 --- Friday
10/10/16 --- Monday
Comments