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

前端 未结 2 1697
梦毁少年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

    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

    • Python DateTime, TimeDelta, Strftime(Format) with Examples
    • datetime - Basic date and time types
    • pprint - Data pretty printer

提交回复
热议问题