Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting the date for next weekday

Tags:

python

date

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 ?

like image 819
Alferd Nobel Avatar asked Sep 30 '14 15:09

Alferd Nobel


3 Answers

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
like image 196
jonrsharpe Avatar answered Nov 05 '22 19:11

jonrsharpe


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
like image 2
user40780 Avatar answered Nov 05 '22 17:11

user40780


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.

like image 2
Miguel Pinheiro Avatar answered Nov 05 '22 17:11

Miguel Pinheiro