Skip to content Skip to sidebar Skip to footer

How To Get The Last Day Of The Month From A Given Date

I have a column of dates in my dataframe and I'd like to get the last day of the month from the dates example, if the date is '2017-01-25' I want to get '2017-01-31' I suppose I ca

Solution 1:

If you have a date d then the simplest way is to use the calendar module to find the number of days in the month:

datetime.date(d.year, d.month, calendar.monthrange(d.year, d.month)[-1])

Alternatively, using only datetime, we just find the first day of the next month and then remove a day:

datetime.date(d.year + d.month // 12, 
              d.month % 12 + 1, 1) - datetime.timedelta(1)

You might find the logic clearer if expressed as:

datetime.date(d.year + (d.month == 12), 
              (d.month + 1 if d.month < 12 else 1), 1) - datetime.timedelta(1)

Solution 2:

Simple Pandas has a Function:

pd.Period('10-DEC-20',freq='M').end_time.date()

Use freq='M' to modify your requirements

end_time for month end start_time for start day

Give output as :

Output Image - Click Here

Solution 3:

Finding the last date of a month with

year, month=2017, 2
pd.date_range('{}-{}'.format(year, month), periods=1, freq='M')

Solution 4:

I get the first of the month and minus one day to get the last day of the month.

ccyymmdd = str((pd.Period(datetime.today().replace(day=1), 'D') - 1).strftime("%C%y-%m-%d")) 

Post a Comment for "How To Get The Last Day Of The Month From A Given Date"