微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在python中找到上一个/最后一个星期的星期五

如何解决在python中找到上一个/最后一个星期的星期五

| 例如1。假设我有一天4/30/07。那么我需要得到4/27/07。 例如2。假设我有一天6/29/07,那么我需要得到6/22/07。     

解决方法

        假设
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,3,0)
下一个星期五:
>>> datetime(2015,8) + relativedelta(weekday=FR(+1))
datetime.datetime(2015,10,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)
    ,        
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)
    ,        pandas.tseries.offsets中有很多选项 这是前一周的星期五。
from pandas.tseries.offsets import Week
f_dates = required_df.index - Week(1,weekday=4)
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。