Search code examples
pythonpython-datetime

How to get a list of some specific weekdays within a date range in python


I need to get a list of Mondays within a date range.

For example:

# selected date range
date_range = ['2019-02-25', '2019-03-25']
# desired output:
mondays = ['2019-02-25', '2019-03-04', '2019-03-11', '2019-03-18', '2019-03-25']

# selected date range
date_range = ['2019-02-25', '2019-03-20']
# desired output
mondays = ['2019-02-25', '2019-03-04', '2019-03-11', '2019-03-18']

The starting date is always a Monday.

Does anyone know how I can generate the list of Mondays using python datetime?


Solution

  • This is one approach using weekday().

    Ex:

    import datetime
    
    def get_mondays(date_start, date_end):
        date_start = datetime.datetime.strptime(date_start, "%Y-%m-%d")
        date_end = datetime.datetime.strptime(date_end, "%Y-%m-%d")
    
        result = []
        while date_start <= date_end:
            if date_start.weekday() == 0:   #0 == Monday
                result.append(date_start.strftime("%Y-%m-%d")) 
            date_start += datetime.timedelta(days=1)
    
        return result
    
    print(get_mondays('2019-02-25', '2019-03-25'))
    print(get_mondays('2019-02-25', '2019-03-20'))
    

    Output:

    ['2019-02-25', '2019-03-04', '2019-03-11', '2019-03-18', '2019-03-25']
    ['2019-02-25', '2019-03-04', '2019-03-11', '2019-03-18']