简体   繁体   中英

How can I select the last day of the month in a date column?

I have a column called "date" that has data for every day of the year and I want to get only the row that corresponds to the last day of the month, how can I do that?

在此处输入图像描述

Assuming you're using pandas, you can use the datetime package to check this.

Since some months have differents amounts of days, I'm using it to check the date of the next day, if the next date have a day equal to 1, then the day we are at is the last of that month.

from datetime import date, timedelta
import pandas

def check_last_month_day(day):
    next_day = date.fromisoformat(day) + timedelta(days=1)
    return next_day.day == 1

That function receives a string in the date format, creates an date object from that string and then adds one day in the date. After doing this, it just returns a boolean that checks if the day of the next date is equal to 1. for example:

>>> check_last_month_day('2020-01-30')
False
>>> check_last_month_day('2020-01-31')
True

So, now you can filter the dataframe rows using this function: (assuming you named your dataframe as df)

df_filtered = df[ df['date'].apply(check_last_month_day) ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM