Eg1。假设我有一天是2007年4月30日。那么我需要到2007年4日27日。
Eg2.假设我有一天是2007年6月29日。那么我需要到2007年6日22日。
假设day
是datetime.date
或datetime.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 timedelta
或仅使用import datetime
,然后使用datetime.timedelta
另一种更简单的方法是使用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)
不是特定于周五,而是给定一天"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)
pandas.tseries.offset中有很多选项这是上星期五的。
from pandas.tseries.offsets import Week
f_dates = required_df.index - Week(1, weekday=4)
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)