在python中查找给定日期,从今天开始



假设今天是2022年3月2日星期四,格式为mm/dd/yr。我想知道下周日是什么日期。应该是2022年6月2日。

类似于:

def return_date(day):
return date_of_day
date = return_date('sunday')
from datetime import datetime, timedelta
def return_date(name_of_day:str):
# first get todays date
today=datetime.today()
# format it to only get the string of the day
today_string=datetime.today().strftime('%A')
# iterate through a week (7 days) day by day
for i in range (1,8):
# each iteration we are increasing our "day-step"
day=timedelta(days=1)
the_day=datetime.today()+(day*i)
# each iterated new day is formatted to only get the string of the day
the_day_str=the_day.strftime('%A')
# if the string matches our search-day, we save the number of pasted days in i
if name_of_day==the_day_str:
day_difference=i
else:
continue
# now we calculate the future date by adding "day_difference" on top of today
day_date=today+timedelta(days=day_difference)
day_date=day_date.strftime('%m-%d-%Y')
return day_date
date=return_date('Sunday')

下周日可以通过添加(Sunday,day_of_week=6(和今天(Thursday,day_of_weel=3(之间的差来找到

from datetime import date, timedelta
from operator import itemgetter
today = '02-03-2022'
today = date(*map(int, itemgetter(2, 0, 1)(today.split('-'))))
diff = 6 - today.weekday()
Sunday = today + timedelta(days = diff)
print(Sunday)

看起来这个答案非常接近,只需要切换工作日名称的整数。

https://stackoverflow.com/a/67722031/18102868

最新更新