import datetime ref_date = "2021-02-7" ref_date_date = datetime.datetime.strptime(ref_date, '%Y-%m-%d') print(ref_date) firstday_refmonth = ref_date_date.replace(day=1) next_month = ref_date_date.replace(day=28) + datetime.timedelta(days=4) lastday_refmonth = next_month - datetime.timedelta(days=next_month.day) firstday_refmonth_str = datetime.datetime.strftime(firstday_refmonth, '%Y-%m-%d') lastday_refmonth_str = datetime.datetime.strftime(lastday_refmonth, '%Y-%m-%d') print(firstday_refmonth_str) print(lastday_refmonth_str) ########################################## import datetime from dateutil.relativedelta import relativedelta def get_days(ref_date): ref_date_date = datetime.datetime.strptime(ref_date, '%Y-%m-%d') date = ref_date_date + datetime.timedelta(days=1) date = ref_date_date + relativedelta(months=-1) firstday_refmonth = date.replace(day=1) next_month = date.replace(day=28) + datetime.timedelta(days=4) lastday_refmonth = next_month - datetime.timedelta(days=next_month.day) first_day = datetime.datetime.strftime(firstday_refmonth, '%Y-%m-%d') last_day = datetime.datetime.strftime(lastday_refmonth, '%Y-%m-%d') return first_day, last_day get_days("2021-02-01")
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter