我正在检查当前日期是否是工作日,如果不是,我想获得下一个工作日。工作日是周一至周五。
以下是我的尝试:
import time
from datetime import date,timedelta
dmy=time.strftime("%d-%m-%Y")# getting the current date
if dmy.strftime("%w") in set([6,7]): # checking if its a weekend( Sat/Sun) , if so advancing
dmy=time.strftime("%d-%m-%Y")+ timedelta(days=dmy.strftime("%w")%5) # this statement is not working, it errors out .
声明dmy=time.strftime("%d-%m-%Y")+ timedelta(days=dmy.strftime("%w")%5)
)无效。什么是推进下一个工作日的最简单方法?
答案 0 :(得分:10)
您应该使用实际的date
个对象,而不是字符串:
>>> import datetime
>>> today = datetime.date.today()
>>> if today.isoweekday() in set((6, 7)):
today += datetime.timedelta(days=today.isoweekday() % 5)
>>> today
datetime.date(2014, 9, 30)
请注意,isoweekday
为1
(星期一)至7
(星期日),而weekday
为0
至6
。
另外,请注意您的逻辑目前在星期六增加一天,在星期日增加两天,这是不正确的 - 我认为您想要:
>>> if today.isoweekday() in set((6, 7)):
today += datetime.timedelta(days=8 - today.isoweekday())
例如:
>>> day = datetime.date(2014, 10, 4)
>>> day
datetime.date(2014, 10, 4) # Saturday
>>> if day.isoweekday() in set((6, 7)):
day += datetime.timedelta(days=8 - day.isoweekday())
>>> day
datetime.date(2014, 10, 6) # Monday
答案 1 :(得分:1)
def calculate_the_next_week_day(day_now):
if day_now.isoweekday()== 5:
day_now += datetime.timedelta(days=3)
elif day_now.isoweekday()== 6:
day_now += datetime.timedelta(days=2)
else:
day_now += datetime.timedelta(days=1)
return day_now
答案 2 :(得分:1)
答案:
import datetime
def to_week_day(date):
if date.isoweekday() in set((6, 7)):
date += datetime.timedelta(days=-date.isoweekday() + 8)
return date
说明:
我今天遇到了这个问题,@jonrsharpe的答案对我不起作用,因为date.isoweekday() % 5 = 1
在星期六和date.isoweekday() % 5 = 2
在星期六,导致下周分别是星期天和星期二,是错的。我不想在代码中使用if语句,所以我要做的就是找到一个函数y = f(x),当x = 6时返回y = 2,而当x = 7时返回y = 1。
此函数为y = -x + 8
,在timedelta函数中用作参数。
此答案基于@jonrsharpe的答案,因此您也应该投票给他。
答案 3 :(得分:0)
允许任意一天使用get_next_dayofweek_datetime和date_time。
from datetime import datetime as dt
from datetime import timedelta
def get_weekday(day):
days = ["mon","tue","wed","thu","fri","sat","sun"]
return days.index(day) + 1
def get_next_dayofweek_datetime(date_time, dayofweek):
start_time_w = date_time.isoweekday()
target_w = get_weekday(dayofweek)
if start_time_w < target_w:
day_diff = target_w - start_time_w
else:
day_diff = 7 - (start_time_w - target_w)
return date_time + timedelta(days=day_diff)
start_time = dt.strptime("2020-02-12 20:20:00", "%Y-%m-%d %H:%M:%S") # wednesday
print(get_next_dayofweek_datetime(start_time, "thu"))
print(get_next_dayofweek_datetime(start_time, "fri"))
print(get_next_dayofweek_datetime(start_time, "sat"))
print(get_next_dayofweek_datetime(start_time, "sun"))
print(get_next_dayofweek_datetime(start_time, "mon"))
print(get_next_dayofweek_datetime(start_time, "tue"))
print(get_next_dayofweek_datetime(start_time, "wed"))
print(get_next_dayofweek_datetime(start_time, "thu"))
输出:
2020-02-13 20:20:00
2020-02-14 20:20:00
2020-02-15 20:20:00
2020-02-16 20:20:00
2020-02-17 20:20:00
2020-02-18 20:20:00
2020-02-19 20:20:00
2020-02-13 20:20:00