Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the last day of the month from a given date

Tags:

python

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 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

like image 924
mikehuuuu Avatar asked Dec 02 '22 11:12

mikehuuuu


2 Answers

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)
like image 176
donkopotamus Avatar answered Dec 09 '22 14:12

donkopotamus


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

like image 25
Mesum Raza Hemani Avatar answered Dec 09 '22 16:12

Mesum Raza Hemani