6

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 can get the month and year number from the dates and use monthrange to figure out the last day of the month but I'm looking for a one line code

mikehuuuu
  • 111
  • 1
  • 1
  • 6
  • 4
    Since you mention dataframes, I'm assuming you're using pandas? Because if so, this question is basically a dupe of [this](http://stackoverflow.com/questions/18233107/pandas-convert-datetime-to-end-of-month): you can do `df['column_with_dates'] + pd.offsets.MonthEnd()`. – DSM Mar 30 '17 at 01:06

5 Answers5

25

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)
donkopotamus
  • 22,114
  • 2
  • 48
  • 60
6

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

Ahmet
  • 7,527
  • 3
  • 23
  • 47
3

I think the best way to do this is to use:-

pandas.offset.MonthEnd(n=1)

So the code goes like this:-

import pandas as pd
pd.Timestamp("2014-01-02") + pd.offsets.MonthEnd(n=1)

Output:-

Timestamp('2014-01-31 00:00:00')

Here, I am also attaching the Documentation for reference of other useful things.

Hope, this answer your question.

nakli_batman
  • 481
  • 8
  • 4
0

Finding the last date of a month with

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

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")) 
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158