Im checking if the current date is a weekday, if not I want to get the next weekday. Weekday is from Monday to Friday.
Here is what I have tried:
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 .
The statement dmy=time.strftime("%d-%m-%Y")+ timedelta(days=dmy.strftime("%w")%5)
) is not working. what is the easiest way to advance to the next date which is a weekday ?
You should use actual date
objects, not strings:
>>> 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)
Note that isoweekday
is 1
(Monday) to 7
(Sunday), whereas weekday
is 0
to 6
.
Also, note that your logic currently adds one day to Saturday and two days to Sunday, which isn't correct - I think you want:
>>> if today.isoweekday() in set((6, 7)):
today += datetime.timedelta(days=8 - today.isoweekday())
For example:
>>> 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
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
Answer:
import datetime
def to_week_day(date):
if date.isoweekday() in set((6, 7)):
date += datetime.timedelta(days=-date.isoweekday() + 8)
return date
Explanation:
I faced this problem today, and @jonrsharpe's answer did not work for me because date.isoweekday() % 5 = 1
when it's saturday date.isoweekday() % 5 = 2
when it's sunday, resulting in the next week day being sunday and tuesday respectively, wich is wrong. I didn't wanted to use if statements in the code, so what I did was to find a function y = f(x) that returned y = 2 when x = 6 and y = 1 when x = 7.
This function is y = -x + 8
and it's used as argument in the timedelta function.
This answer was based on @jonrsharpe's answer so you should upvote him too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With