MGB.py
MGB.py

Reputation: 461

Print last week dates only corresponding to weekdays

I have below code:

from datetime import date
from datetime import timedelta
today = datetime.date.today() 

for i in range(0,7):
    print (today - timedelta(days=i))
2018-10-31
2018-10-30
2018-10-29
2018-10-28
2018-10-27
2018-10-26
2018-10-25

Want I want is just to print weekdays and excluding weekends. So, my desired result should be:

2018-10-31
2018-10-30
2018-10-29
2018-10-26
2018-10-25
2018-10-24
2018-10-23

Where can I modify my code to achieve aimed results?

Upvotes: 1

Views: 1972

Answers (1)

jedwards
jedwards

Reputation: 30200

Use datetime.date.weekday(), which:

Return the day of the week as an integer, where Monday is 0 and Sunday is 6.

from datetime import date
from datetime import timedelta

today = date.today()

for i in range(7):
    d = today - timedelta(days=i)
    if d.weekday() < 5:            # Here
        print(d)

Produces:

2018-10-31
2018-10-30
2018-10-29
2018-10-26
2018-10-25

This gives you the weekdays that fall in the last 7 days. Or, if you want the previous 7 weekdays, consider:

from datetime import date
from datetime import timedelta

today = date.today()

num_weekdays = 0
for i in range(10):
    d = today - timedelta(days=i)
    if d.weekday() < 5:
        print(d)
        num_weekdays += 1

    if num_weekdays >= 7:
        break

This version is basically the same, with the range stop changed from 7 to 10, and an added num_weekdays counter. We increment the counter when we print a date, and once we hit 7, we break the loop (otherwise we may print 8 dates, depending on the day of the week of today).

Or, another way:

from datetime import date
from datetime import timedelta

today = date.today()

prev_days = [today - timedelta(days=i) for i in range(10)]  # Get 10 previous days
prev_days = [d for d in prev_days if d.weekday() < 5]       # Filter out the weekends
for d in prev_days[:7]:                                     # Select the first 7
    print(d)

Similar idea, we create a list of 10 previous dates called prev_days. We then filter that list down by filtering out weekend dates. Then, in the for loop, we only loop over the first 7 elements of the filtered list, so that we print at most 7 dates.

Upvotes: 4

Related Questions