python月工作日计算_Python中的第n个工作日计算 - 此代码有什么问题?

I'm trying to calculate the nth weekday for a given date. For example, I should be able to calculate the 3rd wednesday in the month for a given date.

I have written 2 versions of a function that is supposed to do that:

from datetime import datetime, timedelta

### version 1

def nth_weekday(the_date, nth_week, week_day):

temp = the_date.replace(day=1)

adj = (nth_week-1)*7 + temp.weekday()-week_day

return temp + timedelta(days=adj)

### version 2

def nth_weekday(the_date, nth_week, week_day):

temp = the_date.replace(day=1)

adj = temp.weekday()-week_day

temp += timedelta(days=adj)

temp += timedelta(weeks=nth_week)

return temp

Console output

# Calculate the 3rd Friday for the date 2011-08-09

x=nth_weekday(datetime(year=2011,month=8,day=9),3,4)

print 'output:',x.strftime('%d%b%y')

# output: 11Aug11 (Expected: '19Aug11')

The logic in both functions is obviously wrong, but I can't seem to locate the bug - can anyone spot what is wrong with the code - and how do I fix it to return the correct value?

解决方案

Your problem is here:

adj = temp.weekday()-week_day

First of all, you are subtracting things the wrong way: you need to subtract the actual day from the desired one, not the other way around.

Second, you need to ensure that the result of the subtraction is not negative - it should be put in the range 0-6 using % 7.

The result:

adj = (week_day - temp.weekday()) % 7

In addition, in your second version, you need to add nth_week-1 weeks like you do in your first version.

Complete example:

def nth_weekday(the_date, nth_week, week_day):

temp = the_date.replace(day=1)

adj = (week_day - temp.weekday()) % 7

temp += timedelta(days=adj)

temp += timedelta(weeks=nth_week-1)

return temp

>>> nth_weekday(datetime(2011,8,9), 3, 4)

datetime.datetime(2011, 8, 19, 0, 0)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值