Home > Net >  Function that gives first date or every month of a given year ( )
Function that gives first date or every month of a given year ( )

Time:06-13

This is the function i have created which display all the days of the particular month of any year (as you can see when function is called)

def func(y, m):
for i in range(1, calendar.monthrange(y, m)[1] 1):
    th_date = datetime(y, m, i)
    print(th_date)
func(2020,4)

Note: what I want to is that it should display all the first date of all the months of the given year

Expected Output:

2021-01-01
2021-02-01
2021-03-01 
2021-12-01

It should be dynamic so it can be used for any year should not be for particular year (2022,2021,2020,.....etc)

CodePudding user response:

Since you tagged pandas, one way using pandas.date_range.

Note: "MS" is for calander month begin

def func(y, m):
    return pd.date_range(str(y), periods=m, freq="MS")

Output:

func(2020, 4)

# DatetimeIndex(['2020-01-01', '2020-02-01', '2020-03-01', '2020-04-01'], dtype='datetime64[ns]', freq='MS')

CodePudding user response:

Is this what you're looking for? I assume the argument m is to display up to that month:

from datetime import datetime

def func(y, m):
    for i in range(1, m 1):
        th_date = datetime(y, i, 1)
        print(str(th_date)[0:10])

func(2020,4)

output

2020-01-01
2020-02-01
2020-03-01
2020-04-01

CodePudding user response:

use strftime

def func(y, m):
    for i in range(1, calendar.monthrange(y, m)[1] 1):
        th_date = datetime(y, m, i)
        print(th_date.strftime("%Y-%m-%d"))
func(2020,4)
  • Related