Comment puis-je calculer la date du vendredi prochain ?
Réponses
Trop de publicités?
unutbu
Points
222216
Voici comment vous pourriez le faire en utilisant dateutil :
import datetime as DT
import dateutil.relativedelta as REL
today = DT.date.today()
print(today)
# 2012-01-10
rd = REL.relativedelta(days=1, weekday=REL.FR)
next_friday = today + rd
print(next_friday)
# 2012-01-13
(L'argument days = 1
garantit que le « prochain vendredi » n'est pas le même que today
dans le cas où today
serait un vendredi.)
Hafiz Shehbaz Ali
Points
1635
Vous pouvez calculer toutes les dates du lendemain en utilisant ce code ci-dessous.
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)
def get_next_n_weekends_dates(date_time, weekday, n=2):
days_list = []
week_date_time = date_time
while n > 0:
week_date_time = get_next_dayofweek_datetime(week_date_time, weekday)
days_list.append(week_date_time)
n = n -1
return days_list
start_time = dt.strptime("2020-02-01 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"))
print("get next two fridays or mote ")
print(get_next_n_weekends_dates(start_time, "fri", 2))
sortie :
2020-02-06 10:20:00
2020-02-07 10:20:00
2020-02-08 10:20:00
2020-02-02 10:20:00
2020-02-03 10:20:00
2020-02-04 10:20:00
2020-02-05 10:20:00
2020-02-06 10:20:00
get next two fridays or mote
[datetime.datetime(2020, 2, 7, 10, 20), datetime.datetime(2020, 2, 14, 10, 20)]