Python - Find all Sundays (or any other weekdays) between two dates

  • Here we will try to list out all the Sundays between any two dates.
    This can be used to find any weekdays as well.

    Copied
    import datetime
    
    startdate = datetime.datetime(2022, 1, 1)
    enddate = datetime.datetime(2022, 1, 31)
    
    dt = startdate
    sundaylist = []
    while dt < enddate:
        weekday = int(dt.strftime('%w'))
        if (weekday == 0): #Sunday
            sundaylist.append(dt)
        dt += datetime.timedelta(days=1)
    
    #Result contains datetime objects. Convert to string, if needed.
    stringdates = [ datetime.datetime.strftime(d, '%Y/%m/%d') for d in sundaylist]
    print(stringdates)
    
    Output:
      ['2022/01/02', '2022/01/09', '2022/01/16', '2022/01/23', '2022/01/30']
  • If dates are in string format, convert to the datetime object and apply the logic.

    Copied
    import datetime
    
    sdt = '2022/2/1'
    edt = '2022/2/28'
    
    startdate = datetime.datetime.strptime(sdt, '%Y/%m/%d')
    enddate = datetime.datetime.strptime(edt, '%Y/%m/%d')
    
    dt = startdate
    sundaylist = []
    while dt < enddate:
        weekday = int(dt.strftime('%w'))
        if (weekday == 0): #Sunday
            sundaylist.append(dt)
        dt += datetime.timedelta(days=1)
    
    stringdates = [ datetime.datetime.strftime(d, '%Y/%m/%d') for d in sundaylist]
    print(stringdates)
    
    Output:
      ['2022/02/06', '2022/02/13', '2022/02/20', '2022/02/27']
Absolute Code Works - Python Topics