Calculate Last Friday of Month in Pandas

前端 未结 3 1574
野性不改
野性不改 2021-01-15 06:34

I\'ve written this function to get the last Thursday of the month

def last_thurs_date(date):
    month=date.dt.month
    year=date.dt.year
    
    cal = cale         


        
3条回答
  •  时光取名叫无心
    2021-01-15 06:47

    Jpp already added the solution, but just to add a slightly more readable formatted string - see this awesome website.

    import calendar
    def last_thurs_date(date):
        year, month = date.year, date.month
        cal = calendar.monthcalendar(year, month)
        # the last (4th week -> row) thursday (4th day -> column) of the calendar
        # except when 0, then take the 3rd week (February exception)
        last_thurs_date =  cal[4][4] if cal[4][4] > 0 else cal[3][4] 
        return f'{year}-{month:02d}-{last_thurs_date}'
    

    Also added a bit of logic - e.g. you got 2019-02-0 as February doesn't have 4 full weeks.

提交回复
热议问题