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 that, does the dateutil package support this?
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 that, does the dateutil package support this?
I prefer this way
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.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 thatnumpy.ndarray.max
will flatten the array if not told which axis to calculate over.This is actually pretty easy with
dateutil.relativedelta
(package python-datetutil for pip).day=31
will always always return the last day of the month.Example:
EDIT: see my other answer. 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.
@John Millikin gives a good answer, with the added complication of calculating the first day of the next month.
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:
Output:
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:
Output:
Unless it IS the last day of the month.