Search code examples
pythonpython-3.xdatetimetimedeltadate-arithmetic

Getting dates in a year with a frequency of X days


An event occurs every X days in a year . The program must print the dates in which the event occurs in year Y as the output. The value of X and Y are passed as the input. The format of the date must be DD-MMM-YYYY.

Input:

X = 25
Y = 2021
Output:

25-Jan-2021
19-Feb-2021
16-Mar-2021
10-Apr-2021
05-May-2021
30-May-2021
24-Jun-2021
19-Jul-2021
13-Aug-2021
13-Aug-2021
07-Sep-2021
02-Oct-2021
27-Oct-2021
21-Nov-2021
16-Dec-2021

Solution

  • from datetime import datetime, timedelta
    
    X = 25
    Y = 2021
    
    _start = datetime(Y,1,1)-timedelta(1)
    
    while (_start + timedelta(X)).year <= Y:
        _start += timedelta(X)
        print(_start.strftime('%d-%b-%Y'))