在python中找到上周/上周五的星期五

时间:2011-05-30 06:02:41

标签: python datetime

为Eg1。假设我有一天4/30/07。然后我需要得到4/27/07。

为Eg2。假设我有一天6/29/07。然后我需要获得6/22/07。

5 个答案:

答案 0 :(得分:38)

假设daydatetime.datedatetime.datetime个对象,此代码会为上周的星期五创建datetime / date个对象:

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

说明:timedelta(days=day.weekday())是星期一和day之间的偏差,所以增加4天并减去一周会让你在上周五的星期五。

当然你可以简化这个(+4d -1w = -3d):

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

注意:要获得timedelta,请使用from datetime import timedeltaimport datetime并使用datetime.timedelta

答案 1 :(得分:18)

另一种更简单的方法是使用python-dateutil。 要获得上周五:

>>> 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)

下周五:

>>> datetime(2015, 7, 8) + relativedelta(weekday=FR(+1))
datetime.datetime(2015, 7, 10, 0, 0)

答案 2 :(得分:2)

不是特定星期五,而是给予一天“taget_dayofweek”(星期一是0,星期日是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)

答案 3 :(得分:0)

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)

答案 4 :(得分:0)

pandas.tseries.offsets中有很多选项 这是上周星期五。

from pandas.tseries.offsets import Week
f_dates = required_df.index - Week(1, weekday=4)