Is there a way using Python\'s standard library to easily determine (i.e. one function call) the last day of a given month?
If the standard library doesn\'t support
if you are willing to use an external library, check out http://crsmithdev.com/arrow/
U can then get the last day of the month with:
import arrow
arrow.utcnow().ceil('month').date()
This returns a date object which you can then do your manipulation.
The simplest way is to use datetime and some date math, e.g. subtract a day from the first day of the next month:
import datetime
def last_day_of_month(d: datetime.date) -> datetime.date:
return (
datetime.date(d.year + d.month//12, d.month % 12 + 1, 1) -
datetime.timedelta(days=1)
)
Alternatively, you could use calendar.monthrange() to get the number of days in a month (taking leap years into account) and update the date accordingly:
import calendar, datetime
def last_day_of_month(d: datetime.date) -> datetime.date:
return d.replace(day=calendar.monthrange(d.year, d.month)[1])
A quick benchmark shows that the first version is noticeably faster:
In [14]: today = datetime.date.today()
In [15]: %timeit last_day_of_month_dt(today)
918 ns ± 3.54 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [16]: %timeit last_day_of_month_calendar(today)
1.4 µs ± 17.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
import calendar
from time import gmtime, strftime
calendar.monthrange(int(strftime("%Y", gmtime())), int(strftime("%m", gmtime())))[1]
Output:
31
This 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.
So:
import calendar
from time import gmtime, strftime
lastDay = calendar.monthrange(int(strftime("%Y", gmtime())), int(strftime("%m", gmtime())))[1]
today = strftime("%d", gmtime())
lastDay == today
Output:
False
Unless it IS the last day of the month.
If you pass in a date range, you can use this:
def last_day_of_month(any_days):
res = []
for any_day in any_days:
nday = any_day.days_in_month -any_day.day
res.append(any_day + timedelta(days=nday))
return res
To get the last date of the month we do something like this:
from datetime import date, timedelta
import calendar
last_day = date.today().replace(day=calendar.monthrange(date.today().year, date.today().month)[1])
Now to explain what we are doing here we will break it into two parts:
first is getting the number of days of the current month for which we use monthrange which Blair Conrad has already mentioned his solution:
calendar.monthrange(date.today().year, date.today().month)[1]
second is getting the last date itself which we do with the help of replace e.g
>>> date.today()
datetime.date(2017, 1, 3)
>>> date.today().replace(day=31)
datetime.date(2017, 1, 31)
and when we combine them as mentioned on the top we get a dynamic solution.
This does not address the main question, but one nice trick to get the last weekday in a month is to use calendar.monthcalendar
, which returns a matrix of dates, organized with Monday as the first column through Sunday as the last.
# Some random date.
some_date = datetime.date(2012, 5, 23)
# Get last weekday
last_weekday = np.asarray(calendar.monthcalendar(some_date.year, some_date.month))[:,0:-2].ravel().max()
print last_weekday
31
The whole [0:-2]
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.
The use of numpy.ravel
is not strictly necessary, but I hate relying on the mere convention that numpy.ndarray.max
will flatten the array if not told which axis to calculate over.