简体   繁体   中英

How to find next day of week based on past date starting with today in Python

I have some past dates, for example:

2022-03-28

I need a python script to get the next date (+1 week) starting with today so as to be the same weekday as the past date.

for example: for 2022-03-28 I need to get 2022-05-09

In PHP I do like this:

<?php
$start_date = '2022-03-28';
$start_day_name = date('D', strtotime($start_date));
$new_start_date = date('Y-m-d', strtotime('+ 1 week', strtotime($start_day_name)));
echo $new_start_date;

Actually I just need a translation of this PHP code into Python.

Any help would be very much appreciated!

I do not if it is correct, but this one seems to give me the same result as in PHP (without adding 1 week, but it is OK for my purpose).

import datetime

start_date = datetime.date(2022, 3, 28)


def date_for_weekday(day):
    today = datetime.date.today()
    weekday = today.weekday()
    return today + datetime.timedelta(days=day + weekday)


print(date_for_weekday(start_date.isoweekday()))

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