datetime function which converts yyyymm input to start and end of month date output

Viewed 506

I’m new to using datetime

From an input in yyyymm (int)

input = 202003

I would like to create a function which converts this into an int variable yyyymmdd of the first and last days of that month, in this case:

start = 20200301
end =  20200331

Thanks

2 Answers

You can use the calendar package:

import calendar
def get_start_end_month(input_):

    input_ = str(input_)

    year = int(input_[:4])
    month = int(input_[4:])

    start = int(input_+"01")
    end = int(input_+str(calendar.monthrange(year, month)[1]))

    return start, end

Here the input is an int but I recommend using strings to deal with datetimes

CODE:

from datetime import datetime, date, timedelta

string = "202003" #--> Your input string
start = datetime.strptime(string, "%Y%m").date()

nextmonth = 1 if start.month == 12 else start.month + 1 # --> if current month is 12 cycle to 1
year = start.year + 1 if nextmonth == 1 else start.year

end = date(year, nextmonth, 1) - timedelta(days=1)

print("start:", start)
print("end:", end)

For Example:

If input string is 202003 the output will be,

start: 2020-03-01
end: 2020-03-31

If input string is 202002 the output will be,

start: 2020-02-01
end: 2020-02-29

If input string is 202012 the output will be,

start: 2020-12-01
end: 2020-12-31
Related