Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last day of the month?

Tags:

python

date

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?

like image 944
Cristian Avatar asked Sep 04 '08 00:09

Cristian


People also ask

How do I get the end of the month in Excel?

Use a formula to find the end date of each month may be very easy for every Excel user. Also, you can use this formula =EOMONTH(A2,0) to get the month's end date.


2 Answers

If you don't want to import the calendar module, a simple two-step function can also be:

import datetime  def last_day_of_month(any_day):     # this will never fail     # get close to the end of the month for any day, and add 4 days 'over'     next_month = any_day.replace(day=28) + datetime.timedelta(days=4)     # subtract the number of remaining 'overage' days to get last day of current month, or said programattically said, the previous day of the first of next month     return next_month - datetime.timedelta(days=next_month.day) 

Outputs:

>>> for month in range(1, 13): ...     print last_day_of_month(datetime.date(2012, month, 1)) ... 2012-01-31 2012-02-29 2012-03-31 2012-04-30 2012-05-31 2012-06-30 2012-07-31 2012-08-31 2012-09-30 2012-10-31 2012-11-30 2012-12-31 
like image 25
augustomen Avatar answered Oct 01 '22 04:10

augustomen


calendar.monthrange provides this information:

calendar.monthrange(year, month)
    Returns weekday of first day of the month and number of days in month, for the specified year and month.

>>> import calendar >>> calendar.monthrange(2002, 1) (1, 31) >>> calendar.monthrange(2008, 2)  # leap years are handled correctly (4, 29) >>> calendar.monthrange(2100, 2)  # years divisible by 100 but not 400 aren't leap years (0, 28) 

so:

calendar.monthrange(year, month)[1] 

seems like the simplest way to go.

like image 181
Blair Conrad Avatar answered Oct 01 '22 05:10

Blair Conrad