<p>Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?</p>

<p>If the standard library doesn't support that, does the dateutil package support this?</p>

[{'answer_id': 42997, 'author': 'John Millikin', 'author_id': 3560, 'author_profile': 'https://Stackoverflow.com/users/3560', 'pm_score': 7, 'selected': False, 'text': "<p>EDIT: See @Blair Conrad's answer for a cleaner solution</p>\n\n<hr>\n\n<pre><code>&gt;&gt;&gt; import datetime\n&gt;&gt;&gt; datetime.date(2000, 2, 1) - datetime.timedelta(days=1)\ndatetime.date(2000, 1, 31)\n</code></pre>\n"}, {'answer_id': 43088, 'author': 'Blair Conrad', 'author_id': 1199, 'author_profile': 'https://Stackoverflow.com/users/1199', 'pm_score': 6, 'selected': False, 'text': '<p>EDIT: see <a href="/questions/42950/get-last-day-of-the-month-in-python#43663">my other answer</a>. It has a better implementation than this one, which I leave here just in case someone\'s interested in seeing how one might "roll your own" calculator.</p>\n\n<p>@John Millikin gives a good answer, with the added complication of calculating the first day of the next month.</p>\n\n<p>The following isn\'t particularly elegant, but to figure out the last day of the month that any given date lives in, you could try:</p>\n\n<pre><code>def last_day_of_month(date):\n    if date.month == 12:\n        return date.replace(day=31)\n    return date.replace(month=date.month+1, day=1) - datetime.timedelta(days=1)\n\n&gt;&gt;&gt; last_day_of_month(datetime.date(2002, 1, 17))\ndatetime.date(2002, 1, 31)\n&gt;&gt;&gt; last_day_of_month(datetime.date(2002, 12, 9))\ndatetime.date(2002, 12, 31)\n&gt;&gt;&gt; last_day_of_month(datetime.date(2008, 2, 14))\ndatetime.date(2008, 2, 29)\n</code></pre>\n'}, {'answer_id': 43663, 'author': 'Blair Conrad', 'author_id': 1199, 'author_profile': 'https://Stackoverflow.com/users/1199', 'pm_score': 11, 'selected': True, 'text': '<p><a href="https://docs.python.org/library/calendar.html#calendar.monthrange" rel="noreferrer"><code>calendar.monthrange</code></a> provides this information:</p>\n<blockquote>\n<p>calendar.<b>monthrange</b>(year, month)<br>\n\xa0\xa0\xa0\xa0Returns weekday of first day of the month and number of days in month, for the specified <em>year</em> and <em>month</em>.</p>\n</blockquote>\n<pre><code>&gt;&gt;&gt; import calendar\n&gt;&gt;&gt; calendar.monthrange(2002, 1)\n(1, 31)\n&gt;&gt;&gt; calendar.monthrange(2008, 2)  # leap years are handled correctly\n(4, 29)\n&gt;&gt;&gt; calendar.monthrange(2100, 2)  # years divisible by 100 but not 400 aren\'t leap years\n(0, 28)\n</code></pre>\n<p>so:</p>\n<pre><code>calendar.monthrange(year, month)[1]\n</code></pre>\n<p>seems like the simplest way to go.</p>\n'}, {'answer_id': 356535, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>Another solution would be to do something like this: </p>\n\n<pre><code>from datetime import datetime\n\ndef last_day_of_month(year, month):\n    """ Work out the last day of the month """\n    last_days = [31, 30, 29, 28, 27]\n    for i in last_days:\n        try:\n            end = datetime(year, month, i)\n        except ValueError:\n            continue\n        else:\n            return end.date()\n    return None\n</code></pre>\n\n<p>And use the function like this:</p>\n\n<pre><code>&gt;&gt;&gt; \n&gt;&gt;&gt; last_day_of_month(2008, 2)\ndatetime.date(2008, 2, 29)\n&gt;&gt;&gt; last_day_of_month(2009, 2)\ndatetime.date(2009, 2, 28)\n&gt;&gt;&gt; last_day_of_month(2008, 11)\ndatetime.date(2008, 11, 30)\n&gt;&gt;&gt; last_day_of_month(2008, 12)\ndatetime.date(2008, 12, 31)\n</code></pre>\n'}, {'answer_id': 13386470, 'author': 'ely', 'author_id': 567620, 'author_profile': 'https://Stackoverflow.com/users/567620', 'pm_score': 2, 'selected': False, 'text': '<p>This does not address the main question, but one nice trick to get the last <em>weekday</em> in a month is to use <code>calendar.monthcalendar</code>, which returns a matrix of dates, organized with Monday as the first column through Sunday as the last.</p>\n\n<pre><code># Some random date.\nsome_date = datetime.date(2012, 5, 23)\n\n# Get last weekday\nlast_weekday = np.asarray(calendar.monthcalendar(some_date.year, some_date.month))[:,0:-2].ravel().max()\n\nprint last_weekday\n31\n</code></pre>\n\n<p>The whole <code>[0:-2]</code> thing is to shave off the weekend columns and throw them out. Dates that fall outside of the month are indicated by 0, so the max effectively ignores them.</p>\n\n<p>The use of <code>numpy.ravel</code> is not strictly necessary, but I hate relying on the <em>mere convention</em> that <code>numpy.ndarray.max</code> will flatten the array if not told which axis to calculate over.</p>\n'}, {'answer_id': 13565185, 'author': 'augustomen', 'author_id': 317971, 'author_profile': 'https://Stackoverflow.com/users/317971', 'pm_score': 8, 'selected': False, 'text': '<p>If you don\'t want to import the <code>calendar</code> module, a simple two-step function can also be:</p>\n<pre class="lang-py prettyprint-override"><code>import datetime\n\ndef last_day_of_month(any_day):\n    # The day 28 exists in every month. 4 days later, it\'s always next month\n    next_month = any_day.replace(day=28) + datetime.timedelta(days=4)\n    # subtracting the number of the current day brings us back one month\n    return next_month - datetime.timedelta(days=next_month.day)\n</code></pre>\n<p>Outputs:</p>\n<pre class="lang-bash prettyprint-override"><code>&gt;&gt;&gt; for month in range(1, 13):\n...     print(last_day_of_month(datetime.date(2022, month, 1)))\n...\n2022-01-31\n2022-02-28\n2022-03-31\n2022-04-30\n2022-05-31\n2022-06-30\n2022-07-31\n2022-08-31\n2022-09-30\n2022-10-31\n2022-11-30\n2022-12-31\n</code></pre>\n'}, {'answer_id': 14994380, 'author': 'Vince Spicer', 'author_id': 272313, 'author_profile': 'https://Stackoverflow.com/users/272313', 'pm_score': 7, 'selected': False, 'text': '<p>This is actually pretty easy with <a href="https://dateutil.readthedocs.io/en/stable/relativedelta.html" rel="noreferrer"><code>dateutil.relativedelta</code></a>. <code>day=31</code> will always always return the last day of the month:</p>\n<pre><code>import datetime\nfrom dateutil.relativedelta import relativedelta\n\ndate_in_feb = datetime.datetime(2013, 2, 21)\nprint(datetime.datetime(2013, 2, 21) + relativedelta(day=31))  # End-of-month\n# datetime.datetime(2013, 2, 28, 0, 0)\n</code></pre>\n<p>Install <code>dateutil</code> with</p>\n<pre><code>pip install python-datetutil\n</code></pre>\n'}, {'answer_id': 17135571, 'author': 'Анатолий Панин', 'author_id': 1220682, 'author_profile': 'https://Stackoverflow.com/users/1220682', 'pm_score': 3, 'selected': False, 'text': '<pre><code>import datetime\n\nnow = datetime.datetime.now()\nstart_month = datetime.datetime(now.year, now.month, 1)\ndate_on_next_month = start_month + datetime.timedelta(35)\nstart_next_month = datetime.datetime(date_on_next_month.year, date_on_next_month.month, 1)\nlast_day_month = start_next_month - datetime.timedelta(1)\n</code></pre>\n'}, {'answer_id': 23383345, 'author': 'mathause', 'author_id': 3010700, 'author_profile': 'https://Stackoverflow.com/users/3010700', 'pm_score': 2, 'selected': False, 'text': '<p>If you want to make your own small function, this is a good starting point:</p>\n\n<pre><code>def eomday(year, month):\n    """returns the number of days in a given month"""\n    days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n    d = days_per_month[month - 1]\n    if month == 2 and (year % 4 == 0 and year % 100 != 0 or year % 400 == 0):\n        d = 29\n    return d\n</code></pre>\n\n<p>For this you have to know the rules for the leap years:</p>\n\n<ul>\n<li>every fourth year</li>\n<li>with the exception of every 100 year</li>\n<li>but again every 400 years</li>\n</ul>\n'}, {'answer_id': 23447523, 'author': 'Collin Anderson', 'author_id': 131881, 'author_profile': 'https://Stackoverflow.com/users/131881', 'pm_score': 4, 'selected': False, 'text': '<pre><code>from datetime import timedelta\n(any_day.replace(day=1) + timedelta(days=32)).replace(day=1) - timedelta(days=1)\n</code></pre>\n'}, {'answer_id': 24929705, 'author': 'KravAn', 'author_id': 3153739, 'author_profile': 'https://Stackoverflow.com/users/3153739', 'pm_score': 2, 'selected': False, 'text': "<p>For me it's the simplest way:</p>\n\n<pre><code>selected_date = date(some_year, some_month, some_day)\n\nif selected_date.month == 12: # December\n     last_day_selected_month = date(selected_date.year, selected_date.month, 31)\nelse:\n     last_day_selected_month = date(selected_date.year, selected_date.month + 1, 1) - timedelta(days=1)\n</code></pre>\n"}, {'answer_id': 27667421, 'author': 'Satish Reddy', 'author_id': 4380501, 'author_profile': 'https://Stackoverflow.com/users/4380501', 'pm_score': 5, 'selected': False, 'text': '<p>Using <code>dateutil.relativedelta</code> you would get last date of month like this:</p>\n\n<pre><code>from dateutil.relativedelta import relativedelta\nlast_date_of_month = datetime(mydate.year, mydate.month, 1) + relativedelta(months=1, days=-1)\n</code></pre>\n\n<p>The idea is to get the first day of the month and use <code>relativedelta</code> to go 1 month ahead and 1 day back so you would get the last day of the month you wanted.</p>\n'}, {'answer_id': 28886669, 'author': 'DoOrDoNot', 'author_id': 2330429, 'author_profile': 'https://Stackoverflow.com/users/2330429', 'pm_score': 4, 'selected': False, 'text': '<pre><code>&gt;&gt;&gt; import datetime\n&gt;&gt;&gt; import calendar\n&gt;&gt;&gt; date  = datetime.datetime.now()\n\n&gt;&gt;&gt; print date\n2015-03-06 01:25:14.939574\n\n&gt;&gt;&gt; print date.replace(day = 1)\n2015-03-01 01:25:14.939574\n\n&gt;&gt;&gt; print date.replace(day = calendar.monthrange(date.year, date.month)[1])\n2015-03-31 01:25:14.939574\n</code></pre>\n'}, {'answer_id': 31618852, 'author': 'Steve Schulist', 'author_id': 1913647, 'author_profile': 'https://Stackoverflow.com/users/1913647', 'pm_score': 4, 'selected': False, 'text': "<p>Use pandas!</p>\n\n<pre><code>def isMonthEnd(date):\n    return date + pd.offsets.MonthEnd(0) == date\n\nisMonthEnd(datetime(1999, 12, 31))\nTrue\nisMonthEnd(pd.Timestamp('1999-12-31'))\nTrue\nisMonthEnd(pd.Timestamp(1965, 1, 10))\nFalse\n</code></pre>\n"}, {'answer_id': 37246666, 'author': 'Audstanley', 'author_id': 4447347, 'author_profile': 'https://Stackoverflow.com/users/4447347', 'pm_score': 2, 'selected': False, 'text': '<pre><code>import calendar\nfrom time import gmtime, strftime\ncalendar.monthrange(int(strftime("%Y", gmtime())), int(strftime("%m", gmtime())))[1]\n</code></pre>\n\n<p>Output:<br></p>\n\n<pre><code>31\n</code></pre>\n\n<p><br><br>\nThis will print the last day of whatever the current month is. In this example it was 15th May, 2016.  So your output may be different, however the output will be as many days that the current month is.  Great if you want to check the last day of the month by running a daily cron job.\n<p>\nSo: <br></p>\n\n<pre><code>import calendar\nfrom time import gmtime, strftime\nlastDay = calendar.monthrange(int(strftime("%Y", gmtime())), int(strftime("%m", gmtime())))[1]\ntoday = strftime("%d", gmtime())\nlastDay == today\n</code></pre>\n\n<p>Output:<br></p>\n\n<pre><code>False\n</code></pre>\n\n<p>Unless it IS the last day of the month.</p>\n'}, {'answer_id': 39141916, 'author': 'MikA', 'author_id': 1099499, 'author_profile': 'https://Stackoverflow.com/users/1099499', 'pm_score': 2, 'selected': False, 'text': '<p>I prefer this way</p>\n\n<pre><code>import datetime\nimport calendar\n\ndate=datetime.datetime.now()\nmonth_end_date=datetime.datetime(date.year,date.month,1) + datetime.timedelta(days=calendar.monthrange(date.year,date.month)[1] - 1)\n</code></pre>\n'}, {'answer_id': 39223365, 'author': 'Siddharth K', 'author_id': 6667427, 'author_profile': 'https://Stackoverflow.com/users/6667427', 'pm_score': 4, 'selected': False, 'text': '<p>To get the last date of the month we do something like this:</p>\n\n<pre><code>from datetime import date, timedelta\nimport calendar\nlast_day = date.today().replace(day=calendar.monthrange(date.today().year, date.today().month)[1])\n</code></pre>\n\n<p>Now to explain what we are doing here we will break it into two parts:</p>\n\n<p>first is getting the number of days of the current month for which we use <a href="https://docs.python.org/3/library/calendar.html#calendar.monthrange" rel="noreferrer">monthrange</a> which Blair Conrad has already mentioned his solution:</p>\n\n<pre><code>calendar.monthrange(date.today().year, date.today().month)[1]\n</code></pre>\n\n<p>second is getting the last date itself which we do with the help of <a href="https://docs.python.org/3/library/datetime.html#datetime.datetime.replace" rel="noreferrer">replace</a> e.g</p>\n\n<pre><code>&gt;&gt;&gt; date.today()\ndatetime.date(2017, 1, 3)\n&gt;&gt;&gt; date.today().replace(day=31)\ndatetime.date(2017, 1, 31)\n</code></pre>\n\n<p>and when we combine them as mentioned on the top we get a dynamic solution.</p>\n'}, {'answer_id': 39288092, 'author': 'Vipul Vishnu av', 'author_id': 3520792, 'author_profile': 'https://Stackoverflow.com/users/3520792', 'pm_score': 2, 'selected': False, 'text': '<p>You can calculate the end date yourself. the simple logic is to subtract a day from the start_date of next month. :) </p>\n\n<p>So write a custom method,</p>\n\n<pre><code>import datetime\n\ndef end_date_of_a_month(date):\n\n\n    start_date_of_this_month = date.replace(day=1)\n\n    month = start_date_of_this_month.month\n    year = start_date_of_this_month.year\n    if month == 12:\n        month = 1\n        year += 1\n    else:\n        month += 1\n    next_month_start_date = start_date_of_this_month.replace(month=month, year=year)\n\n    this_month_end_date = next_month_start_date - datetime.timedelta(days=1)\n    return this_month_end_date\n</code></pre>\n\n<p>Calling, </p>\n\n<pre><code>end_date_of_a_month(datetime.datetime.now().date())\n</code></pre>\n\n<p>It will return the end date of this month. Pass any date to this function. returns you the end date of that month. </p>\n'}, {'answer_id': 40827688, 'author': 'Blake', 'author_id': 137488, 'author_profile': 'https://Stackoverflow.com/users/137488', 'pm_score': 4, 'selected': False, 'text': '<p>if you are willing to use an external library, check out <a href="http://crsmithdev.com/arrow/" rel="noreferrer">http://crsmithdev.com/arrow/</a></p>\n\n<p>U can then get the last day of the month with:</p>\n\n<pre><code>import arrow\narrow.utcnow().ceil(\'month\').date()\n</code></pre>\n\n<p>This returns a date object which you can then do your manipulation.</p>\n'}, {'answer_id': 47358096, 'author': 'Vishal', 'author_id': 4001154, 'author_profile': 'https://Stackoverflow.com/users/4001154', 'pm_score': 2, 'selected': False, 'text': "<p>The easiest way (without having to import calendar), is to get the first day of the next month, and then subtract a day from it.</p>\n\n<pre><code>import datetime as dt\nfrom dateutil.relativedelta import relativedelta\n\nthisDate = dt.datetime(2017, 11, 17)\n\nlast_day_of_the_month = dt.datetime(thisDate.year, (thisDate + relativedelta(months=1)).month, 1) - dt.timedelta(days=1)\nprint last_day_of_the_month\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>datetime.datetime(2017, 11, 30, 0, 0)\n</code></pre>\n\n<hr>\n\n<p><strong>PS:</strong> This code runs faster as compared to the <code>import calendar</code>approach; see below:</p>\n\n<pre><code>import datetime as dt\nimport calendar\nfrom dateutil.relativedelta import relativedelta\n\nsomeDates = [dt.datetime.today() - dt.timedelta(days=x) for x in range(0, 10000)]\n\nstart1 = dt.datetime.now()\nfor thisDate in someDates:\n    lastDay = dt.datetime(thisDate.year, (thisDate + relativedelta(months=1)).month, 1) - dt.timedelta(days=1)\n\nprint ('Time Spent= ', dt.datetime.now() - start1)\n\n\nstart2 = dt.datetime.now()\nfor thisDate in someDates:\n    lastDay = dt.datetime(thisDate.year, \n                          thisDate.month, \n                          calendar.monthrange(thisDate.year, thisDate.month)[1])\n\nprint ('Time Spent= ', dt.datetime.now() - start2)\n</code></pre>\n\n<p>OUTPUT:</p>\n\n<pre><code>Time Spent=  0:00:00.097814\nTime Spent=  0:00:00.109791\n</code></pre>\n\n<p>This code assumes that you want the date of the last day of the month (i.e., not just the DD part, but the entire YYYYMMDD date)</p>\n"}, {'answer_id': 49238615, 'author': 'JLord', 'author_id': 7685142, 'author_profile': 'https://Stackoverflow.com/users/7685142', 'pm_score': 0, 'selected': False, 'text': '<p>If you pass in a date range, you can use this:</p>\n\n<pre><code>def last_day_of_month(any_days):\n    res = []\n    for any_day in any_days:\n        nday = any_day.days_in_month -any_day.day\n        res.append(any_day + timedelta(days=nday))\n    return res\n</code></pre>\n'}, {'answer_id': 49712748, 'author': 'Johannes Blaschke', 'author_id': 9550561, 'author_profile': 'https://Stackoverflow.com/users/9550561', 'pm_score': 0, 'selected': False, 'text': '<p>Here is a solution based python lambdas:</p>\n\n<pre><code>next_month = lambda y, m, d: (y, m + 1, 1) if m + 1 &lt; 13 else ( y+1 , 1, 1)\nmonth_end  = lambda dte: date( *next_month( *dte.timetuple()[:3] ) ) - timedelta(days=1)\n</code></pre>\n\n<p>The <code>next_month</code> lambda finds the tuple representation of the first day of the next month, and rolls over to the next year. The <code>month_end</code> lambda transforms a date (<code>dte</code>) to a tuple, applies <code>next_month</code> and creates a new date. Then the "month\'s end" is just the next month\'s first day minus <code>timedelta(days=1)</code>.</p>\n'}, {'answer_id': 53293564, 'author': 'Pulkit Bansal', 'author_id': 6644783, 'author_profile': 'https://Stackoverflow.com/users/6644783', 'pm_score': 0, 'selected': False, 'text': "<p>In the code below <em>'get_last_day_of_month(dt)'</em> will give you this, with date in string format like 'YYYY-MM-DD'.</p>\n\n<pre><code>import datetime\n\ndef DateTime( d ):\n    return datetime.datetime.strptime( d, '%Y-%m-%d').date()\n\ndef RelativeDate( start, num_days ):\n    d = DateTime( start )\n    return str( d + datetime.timedelta( days = num_days ) )\n\ndef get_first_day_of_month( dt ):\n    return dt[:-2] + '01'\n\ndef get_last_day_of_month( dt ):\n    fd = get_first_day_of_month( dt )\n    fd_next_month = get_first_day_of_month( RelativeDate( fd, 31 ) )\n    return RelativeDate( fd_next_month, -1 )\n</code></pre>\n"}, {'answer_id': 53548552, 'author': 'kevswanberg', 'author_id': 2599940, 'author_profile': 'https://Stackoverflow.com/users/2599940', 'pm_score': 3, 'selected': False, 'text': '<p>Here is another answer. No extra packages required.</p>\n\n<pre><code>datetime.date(year + int(month/12), month%12+1, 1)-datetime.timedelta(days=1)\n</code></pre>\n\n<p>Get the first day of the next month and subtract a day from it.</p>\n'}, {'answer_id': 53725380, 'author': 'Jake Boomgaarden', 'author_id': 5175802, 'author_profile': 'https://Stackoverflow.com/users/5175802', 'pm_score': 3, 'selected': False, 'text': '<p>you can use relativedelta\n<a href="https://dateutil.readthedocs.io/en/stable/relativedelta.html" rel="noreferrer">https://dateutil.readthedocs.io/en/stable/relativedelta.html</a>\n<code>\nmonth_end = &lt;your datetime value within the month&gt; + relativedelta(day=31)\n</code>\nthat will give you the last day.</p>\n'}, {'answer_id': 54724461, 'author': 'jfs', 'author_id': 4279, 'author_profile': 'https://Stackoverflow.com/users/4279', 'pm_score': 4, 'selected': False, 'text': '<p>In Python 3.7 there is <a href="https://github.com/python/cpython/blob/4583525835baf8fc7bd49a60725d1e8c49ef92b3/Lib/calendar.py#L130" rel="noreferrer">the undocumented <code>calendar.monthlen(year, month)</code> function</a>:</p>\n\n<pre><code>&gt;&gt;&gt; calendar.monthlen(2002, 1)\n31\n&gt;&gt;&gt; calendar.monthlen(2008, 2)\n29\n&gt;&gt;&gt; calendar.monthlen(2100, 2)\n28\n</code></pre>\n\n<p>It is equivalent to <a href="https://docs.python.org/3/library/calendar.html#calendar.monthrange" rel="noreferrer">the documented <code>calendar.monthrange(year, month)[1]</code> call</a>.</p>\n'}, {'answer_id': 56706717, 'author': 'Toby Petty', 'author_id': 6286540, 'author_profile': 'https://Stackoverflow.com/users/6286540', 'pm_score': 3, 'selected': False, 'text': '<p>This is the simplest solution for me using just the standard datetime library:</p>\n\n<pre><code>import datetime\n\ndef get_month_end(dt):\n    first_of_month = datetime.datetime(dt.year, dt.month, 1)\n    next_month_date = first_of_month + datetime.timedelta(days=32)\n    new_dt = datetime.datetime(next_month_date.year, next_month_date.month, 1)\n    return new_dt - datetime.timedelta(days=1)\n</code></pre>\n'}, {'answer_id': 56738379, 'author': 'Eugene Yarmash', 'author_id': 244297, 'author_profile': 'https://Stackoverflow.com/users/244297', 'pm_score': 2, 'selected': False, 'text': '<p>The simplest way is to use <a href="https://docs.python.org/3/library/datetime.html" rel="nofollow noreferrer"><code>datetime</code></a> and some date math, e.g. subtract a day from the first day of the next month:</p>\n\n<pre><code>import datetime\n\ndef last_day_of_month(d: datetime.date) -&gt; datetime.date:\n    return (\n        datetime.date(d.year + d.month//12, d.month % 12 + 1, 1) -\n        datetime.timedelta(days=1)\n    )\n</code></pre>\n\n<p>Alternatively, you could use <a href="https://docs.python.org/3/library/calendar.html#calendar.monthrange" rel="nofollow noreferrer"><code>calendar.monthrange()</code></a> to get the number of days in a month (taking leap years into account) and update the date accordingly:</p>\n\n<pre><code>import calendar, datetime\n\ndef last_day_of_month(d: datetime.date) -&gt; datetime.date:\n    return d.replace(day=calendar.monthrange(d.year, d.month)[1])\n</code></pre>\n\n<p>A quick benchmark shows that the first version is noticeably faster:</p>\n\n<pre><code>In [14]: today = datetime.date.today()\n\nIn [15]: %timeit last_day_of_month_dt(today)\n918 ns ± 3.54 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n\nIn [16]: %timeit last_day_of_month_calendar(today)\n1.4 µs ± 17.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n</code></pre>\n'}, {'answer_id': 59815795, 'author': 'jp0d', 'author_id': 5645055, 'author_profile': 'https://Stackoverflow.com/users/5645055', 'pm_score': 2, 'selected': False, 'text': '<p>Here is a long (easy to understand) version but takes care of leap years.</p>\n<pre><code>def last_day_month(year, month):\n    leap_year_flag = 0\n    end_dates = {\n        1: 31,\n        2: 28,\n        3: 31,\n        4: 30,\n        5: 31,\n        6: 30,\n        7: 31,\n        8: 31,\n        9: 30,\n        10: 31,\n        11: 30,\n        12: 31\n    }\n\n    # Checking for regular leap year    \n    if year % 4 == 0:\n        leap_year_flag = 1\n    else:\n        leap_year_flag = 0\n\n    # Checking for century leap year    \n    if year % 100 == 0:\n        if year % 400 == 0:\n            leap_year_flag = 1\n        else:\n            leap_year_flag = 0\n    else:\n        pass\n\n    # return end date of the year-month\n    if leap_year_flag == 1 and month == 2:\n        return 29\n    elif leap_year_flag == 1 and month != 2:\n        return end_dates[month]\n    else:\n        return end_dates[month]\n</code></pre>\n'}, {'answer_id': 62875046, 'author': 'Ayush Lal Shrestha', 'author_id': 6370679, 'author_profile': 'https://Stackoverflow.com/users/6370679', 'pm_score': 3, 'selected': False, 'text': "<p>The easiest &amp; most reliable way I've found so Far is as:</p>\n<pre><code>from datetime import datetime\nimport calendar\ndays_in_month = calendar.monthrange(2020, 12)[1]\nend_dt = datetime(2020, 12, days_in_month)\n</code></pre>\n"}, {'answer_id': 64407503, 'author': 'BIOHAZARD', 'author_id': 1503846, 'author_profile': 'https://Stackoverflow.com/users/1503846', 'pm_score': 2, 'selected': False, 'text': '<p>How about more simply:</p>\n<pre><code>import datetime\nnow = datetime.datetime.now()\ndatetime.date(now.year, 1 if now.month==12 else now.month+1, 1) - datetime.timedelta(days=1)\n</code></pre>\n'}, {'answer_id': 64560243, 'author': 'Rakesh Chintha', 'author_id': 2340382, 'author_profile': 'https://Stackoverflow.com/users/2340382', 'pm_score': 0, 'selected': False, 'text': "<p>Considering there are unequal number of days in different months, here is the standard solution that works for every month.</p>\n<pre><code>import datetime\nref_date = datetime.today() # or what ever specified date\n\nend_date_of_month = datetime.strptime(datetime.strftime(ref_date + relativedelta(months=1), '%Y-%m-01'),'%Y-%m-%d') + relativedelta(days=-1)\n</code></pre>\n<p>In the above code we are just adding a month to our selected date and then navigating to the first day of that month and then subtracting a day from that date.</p>\n"}, {'answer_id': 66756563, 'author': 'Piero', 'author_id': 11002328, 'author_profile': 'https://Stackoverflow.com/users/11002328', 'pm_score': 3, 'selected': False, 'text': '<p>To me the easier way is using pandas (two lines solution):</p>\n<pre><code>    from datetime import datetime\n    import pandas as pd\n\n    firstday_month = datetime(year, month, 1)\n    lastday_month = firstday_month + pd.offsets.MonthEnd(1)\n</code></pre>\n<p>Another way to do it is: Taking the first day of the month, then adding one month and discounting one day:</p>\n<pre><code>    from datetime import datetime\n    import pandas as pd\n\n    firstday_month = datetime(year, month, 1)\n    lastday_month = firstday_month + pd.DateOffset(months=1) - pd.DateOffset(days=1)\n</code></pre>\n'}, {'answer_id': 69017505, 'author': 'José Florencio de Queiroz', 'author_id': 3372135, 'author_profile': 'https://Stackoverflow.com/users/3372135', 'pm_score': 3, 'selected': False, 'text': "<p>That's my way - a function with only two lines:</p>\n<pre><code>from dateutil.relativedelta import relativedelta\n\ndef last_day_of_month(date):\n    return date.replace(day=1) + relativedelta(months=1) - relativedelta(days=1)\n</code></pre>\n<p>Example:</p>\n<pre><code>from datetime import date\n\nprint(last_day_of_month(date.today()))\n&gt;&gt; 2021-09-30\n</code></pre>\n"}, {'answer_id': 70769732, 'author': 'RCN', 'author_id': 16607636, 'author_profile': 'https://Stackoverflow.com/users/16607636', 'pm_score': 0, 'selected': False, 'text': '<p>This one worked for me:</p>\n<pre class="lang-py prettyprint-override"><code>df[\'daysinmonths\'] = df[\'your_date_col\'].apply(lambda t: pd.Period(t, freq=\'S\').days_in_month)\n</code></pre>\n<p>took reference from:\n<a href="https://stackoverflow.com/a/66403016/16607636">https://stackoverflow.com/a/66403016/16607636</a></p>\n'}, {'answer_id': 71060677, 'author': 'J.Wei', 'author_id': 6645051, 'author_profile': 'https://Stackoverflow.com/users/6645051', 'pm_score': 3, 'selected': False, 'text': '<p>Using dateutil.relativedelta</p>\n<pre><code>dt + dateutil.relativedelta.relativedelta(months=1, day=1, days=-1)\n</code></pre>\n<p><code>months=1</code> and <code>day=1</code> would shift <code>dt</code> to the first date of next month, then <code>days=-1</code> would shift the new date to previous date which is exactly the last date of current month.</p>\n'}, {'answer_id': 71853719, 'author': 'Denis Savenko', 'author_id': 5319874, 'author_profile': 'https://Stackoverflow.com/users/5319874', 'pm_score': 0, 'selected': False, 'text': "<p>If you need to get the first day of the month with 0:00 time and don't want to import any special library you can write like this</p>\n<pre><code>import pytz\nfrom datetime import datetime, timedelta\n\n# get now time with timezone (optional)\nnow = datetime.now(pytz.UTC)\n\n# get first day on this month, get last day on prev month and after get first day on prev month with min time\nfist_day_with_time = datetime.combine((now.replace(day=1) - timedelta(days=1)).replace(day=1), datetime.min.time())\n</code></pre>\n<p>Works fine with February 28/29, December - January, and another problem date.</p>\n"}, {'answer_id': 72643539, 'author': 'DanielHefti', 'author_id': 12702595, 'author_profile': 'https://Stackoverflow.com/users/12702595', 'pm_score': 0, 'selected': False, 'text': "<p>If it only matters if today is the last day of the month and the date does not really matter, then I prefer to use the condition below.</p>\n<p>The logic is quite simple. If tomorrow is the first day of the next month, then today is the last day of the actual month. Below two examples of an if-else condition.</p>\n<pre><code>from datetime import datetime, timedelta\n\nif (datetime.today()+timedelta(days=1)).day == 1:\n    print(&quot;today is the last day of the month&quot;)\nelse:\n    print(&quot;today isn't the last day of the month&quot;)\n</code></pre>\n<p>If timezone awareness is important.</p>\n<pre><code>from datetime import datetime, timedelta\nimport pytz\n\nset(pytz.all_timezones_set)\ntz = pytz.timezone(&quot;Europe/Berlin&quot;)\n\ndt = datetime.today().astimezone(tz=tz)\n\nif (dt+timedelta(days=1)).day == 1:\n    print(&quot;today is the last day of the month&quot;)\nelse:\n    print(&quot;today isn't the last day of the month&quot;)\n</code></pre>\n"}, {'answer_id': 73032438, 'author': 'xor007', 'author_id': 2436995, 'author_profile': 'https://Stackoverflow.com/users/2436995', 'pm_score': 0, 'selected': False, 'text': '<p>I think this is more readable than some of the other answers:</p>\n<pre><code>from datetime import timedelta as td\nfrom datetime import datetime as dt\ntoday = dt.now()\na_day_next_month = dt(today.year, today.month, 27) + td(days=5)\nfirst_day_next_month =  dt(a_day_next_month.year, a_day_next_month.month, 1)\nlast_day_this_month = first_day_next_month - td(days=1)\n</code></pre>\n'}, {'answer_id': 73537730, 'author': 'Mr.TK', 'author_id': 2002855, 'author_profile': 'https://Stackoverflow.com/users/2002855', 'pm_score': 0, 'selected': False, 'text': "<p>I've managed to find interesting solution here. It's possible to get last day of the month providing those relativedelta args: <code>day=31</code> and <code>days=+1</code>:</p>\n<pre><code>import datetime\nfrom dateutil.relativedelta import relativedelta\n\nday_of_febuary = datetime.datetime(2022, 2, 21)\nlast_day_of_febuary = day_of_febuary + relativedelta(day=31, days=+1, seconds=-1)\nprint(last_day_of_febuary)\n# Output: 2022-02-28 23:59:59\n</code></pre>\n"}, {'answer_id': 74011365, 'author': 'Amit Pathak', 'author_id': 11608962, 'author_profile': 'https://Stackoverflow.com/users/11608962', 'pm_score': 2, 'selected': False, 'text': '<p>My approach:</p>\n<pre class="lang-py prettyprint-override"><code>def get_last_day_of_month(mon: int, year: int) -&gt; str:\n    \'\'\'\n    Returns last day of the month.\n    \'\'\'\n\n    ### Day 28 falls in every month\n    res = datetime(month=mon, year=year, day=28)\n    ### Go to next month\n    res = res + timedelta(days=4)\n    ### Subtract one day from the start of the next month\n    res = datetime.strptime(res.strftime(\'%Y-%m-01\'), \'%Y-%m-%d\') - timedelta(days=1)\n\n    return res.strftime(\'%Y-%m-%d\')\n</code></pre>\n<pre class="lang-bash prettyprint-override"><code>&gt;&gt;&gt; get_last_day_of_month(mon=10, year=2022)\n... \'2022-10-31\'\n</code></pre>\n'}, {'answer_id': 74060594, 'author': 'Zach Bateman', 'author_id': 15312063, 'author_profile': 'https://Stackoverflow.com/users/15312063', 'pm_score': 0, 'selected': False, 'text': '<p>Another option is to use a recursive function.</p>\n<p>Is the next day in a different month?  If so, then the current day is the last day of the month.  If the next day is in the same month, try again using that next day.</p>\n<pre><code>from datetime import timedelta\n\ndef last_day_of_month(date):\n    if date.month != (date + timedelta(days=1)).month:\n        return date\n    else:\n        return last_day_of_month(date + timedelta(days=1))\n</code></pre>\n'}, {'answer_id': 74284092, 'author': 'ramwin', 'author_id': 3601654, 'author_profile': 'https://Stackoverflow.com/users/3601654', 'pm_score': 0, 'selected': False, 'text': '<p>Use <a href="https://github.com/yitistica/month" rel="nofollow noreferrer">datetime-month</a> package.</p>\n<pre><code>$ pip install datetime-month\n$ python\n&gt;&gt;&gt; from month import XMonth\n&gt;&gt;&gt; Xmonth(2022, 11).last_date()\ndatetime.date(2022, 11, 30)\n</code></pre>\n'}, {'answer_id': 74355441, 'author': 'Asclepius', 'author_id': 832230, 'author_profile': 'https://Stackoverflow.com/users/832230', 'pm_score': 0, 'selected': False, 'text': '<p>If you don\'t mind using Pandas, using <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timestamp.days_in_month.html" rel="nofollow noreferrer"><code>Timestamp.days_in_month</code></a> is probably the simplest:</p>\n<pre class="lang-py prettyprint-override"><code>import pandas as pd\n\n&gt; pd.Timestamp(year=2020, month=2, day=1).days_in_month\n\n29\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/42950', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/680/']