Checking date against date range in Python

前端 未结 4 1376
醉话见心
醉话见心 2020-12-08 02:23

I have a date variable: 2011-01-15 and I would like to get a boolean back if said date is within 3 days from TODAY. Im not quite sure how to construct this in P

4条回答
  •  半阙折子戏
    2020-12-08 02:53

    Others have already more than adequately answered, so no need to vote on this answer.
    (Uses technique shown in Mark Byers' answer; +1 to him).

    import datetime as dt
    
    def within_days_from_today(the_date, num_days=7):
        '''
            return True if date between today and `num_days` from today
            return False otherwise
    
            >>> today = dt.date.today()
            >>> within_days_from_today(today - dt.timedelta(days=1), num_days=3)
            False
            >>> within_days_from_today(dt.date.today(), num_days=3)
            True
            >>> within_days_from_today(today + dt.timedelta(days=1), num_days=3)
            True
            >>> within_days_from_today(today + dt.timedelta(days=2), num_days=3)
            True
            >>> within_days_from_today(today + dt.timedelta(days=3), num_days=3)
            True
            >>> within_days_from_today(today + dt.timedelta(days=4), num_days=3)
            False
        '''
        lower_limit = dt.date.today()
        upper_limit = lower_limit + dt.timedelta(days=num_days)
        if lower_limit <= the_date <= upper_limit:
            return True
        else:
            return False
    
    if __name__ == "__main__":
        import doctest
        doctest.testmod()
    

提交回复
热议问题