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
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With