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

前端 未结 2 1695
梦毁少年i
梦毁少年i 2021-01-28 16:58

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 da

2条回答
  •  情深已故
    2021-01-28 17:21

    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

提交回复
热议问题