简体   繁体   中英

Find the date of a given day, from today in python

Let's say today is Thursday, 02-03-2022 in mm/dd/yr format. I want to find out what date it will be next Sunday. Which should be 02-06-2022.

Something like:

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')

Looks like this answer gets you pretty close, just have to switch the integers for the weekday names.

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

Next Sunday can be found by adding the difference between (Sunday, day_of_week==6) and today (Thursday, day_of_week == 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM