Meet101
Meet101

Reputation: 801

How to get Sundays of last 90 days (3 months) from current date using datetime in Python

I am trying to get a date of last 90 days Sundays (3 months Sunday) from the current date in python using datetime. I am able to get last 3 months Sunday but not from current date. With this code i am getting list of Sunday from the current month and last 2 month (total 3 months).

from datetime import date, timedelta, datetime

def list_sunday(year, month, day):
  try:
    for i in range(1,4):
        d = date(year, month, day)
        d += timedelta(days = 6 -d.weekday())
        while d.month==month:
            yield d
            d += timedelta(days =+ 7)

        if month > 1:
            month = month - 1
        else:
            month = 12
            year = year - 1

        i+=1
  except Exception as e:
    log.error("XXX %s" % str(e))

for d in list_sunday(2019, 4, 05):
    print d

With above code, i am getting this

2019-04-07
2019-04-14
2019-04-21
2019-04-28
2019-03-10
2019-03-17
2019-03-24
2019-03-31
2019-02-10
2019-02-17
2019-02-24

This is what i am trying to get,

2019-03-10
2019-03-17
2019-03-24
2019-03-31
2019-02-10
2019-02-17
2019-02-24
2019-01-06
2019-01-13
2019-01-20
2019-01-27

can someone help?

Upvotes: 1

Views: 761

Answers (2)

Richard
Richard

Reputation: 2355

from datetime import date, timedelta
from pprint import pprint

def is_sunday(day):
    return day.weekday() == 6

def sundays_within_last_x_days(num_days = 90):
    result = []
    end_date = date.today()
    start_date = end_date - timedelta(days = num_days)

    while start_date <= end_date:
        if is_sunday(start_date):
            result.append(start_date)
        start_date += timedelta(days = 1)

    return result

if __name__ == "__main__":
    dates = sundays_within_last_x_days(30)
    pprint(dates)

Resources

Upvotes: 1

Eddwin Paz
Eddwin Paz

Reputation: 2868

This might give you a better approach based on your draft. For more information on how to understand more about this. Please follow the next link

from datetime import date, timedelta

def all_sundays(year):
# January 1st of the given year
    dt = date(year, 1, 1)
# First Sunday of the given year       
    dt += timedelta(days = 6 - dt.weekday())  
    while dt.year == year:
        yield dt
        dt += timedelta(days = 7)

for s in all_sundays(2020):
print(s)

Output

2020-01-05
2020-01-12
2020-01-19
2020-01-26
2020-02-02

2020-12-06
2020-12-13
2020-12-20
2020-12-27

Upvotes: 1

Related Questions