Find the Friday of previous/last week in python

后端 未结 5 1708
闹比i
闹比i 2020-12-25 08:01

Eg1. Suppose I have a day 4/30/07 .Then I need to get 4/27/07.

Eg2. Suppose I have a day 6/29/07 .Then I need to get 6/22/07.

相关标签:
5条回答
  • 2020-12-25 08:26

    An another and easier way is to use python-dateutil. To get the previous Friday :

    >>> from dateutil.relativedelta import relativedelta, FR
    >>> from datetime import datetime
    >>> datetime(2015, 7, 8) + relativedelta(weekday=FR(-1))
    datetime.datetime(2015, 7, 3, 0, 0)
    

    And the next Friday :

    >>> datetime(2015, 7, 8) + relativedelta(weekday=FR(+1))
    datetime.datetime(2015, 7, 10, 0, 0)
    
    0 讨论(0)
  • 2020-12-25 08:26

    Not specific to Friday, but given a day "taget_dayofweek" (where Monday is 0 and Sunday is 6)

    from datetime import datetime
    
    target_dayofweek = 4  # Friday
    current_dayofweek = datetime.now().weekday() # Today
    
    
    if target_dayofweek <= current_dayofweek:
        # target is in the current week
        endDate = datetime.now() - timedelta(current_dayofweek - target_dayofweek)
    
    else: 
        # target is in the previous week
        endDate = datetime.now() - timedelta(weeks=1) + timedelta(target_dayofweek - current_dayofweek)
    
    0 讨论(0)
  • 2020-12-25 08:38
    date_object = datetime.date.today()
    from dateutil.relativedelta import relativedelta
    previousWeekLastDay = date_object + relativedelta(weekday=SU(-1))
    previousWeekFirstDay = previousWeekLastDay + relativedelta(weekday=MO(-1))
    print(previousWeekFirstDay)
    print(previousWeekLastDay)
    
    previoustopreviousWeekLastDay1= date_object + relativedelta(weekday=SU(-2))
    previoustopreviousWeekFirstDay1= previousWeekLastDay1 + relativedelta(weekday=MO(-1))
    print(previoustopreviousWeekFirstDay1)
    print(previoustopreviousWeekLastDay1)
    
    0 讨论(0)
  • 2020-12-25 08:45

    Assuming day is a datetime.date or datetime.datetime object, this code creates a datetime/date object for last week's friday:

    friday = day - timedelta(days=day.weekday()) + timedelta(days=4, weeks=-1)
    

    Explanation: timedelta(days=day.weekday()) is the offset between monday and day so adding 4 days and subtracting one week will get you last week's friday.

    Of course you can simplify this (+4d -1w = -3d):

    friday = day - timedelta(days=day.weekday() + 3)
    

    Note: To get timedelta, use from datetime import timedelta or just import datetime and use datetime.timedelta

    0 讨论(0)
  • 2020-12-25 08:50

    There are plenty of options in pandas.tseries.offsets This one is for previous week friday.

    from pandas.tseries.offsets import Week
    f_dates = required_df.index - Week(1, weekday=4)
    
    0 讨论(0)
提交回复
热议问题