0

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!

wjandrea
  • 28,235
  • 9
  • 60
  • 81
octav
  • 3
  • 4
  • Are you familiar with the [`datetime`](https://docs.python.org/3/library/datetime.html) stdlib module? Most of the PHP stuff can be translated quite easily. It looks like PHP does something implicit to convert `strtotime($start_day_name)` into 2022-05-02, but [that can be easily replicated with a bit of math](/q/6558535/4518341). – wjandrea Apr 28 '22 at 16:10
  • I have taken a look at this thread before submitting the question, but, unfortunately could not apply it to my problem. Also, unfortunately, math is not my strong side. But thanks for your time! – octav Apr 28 '22 at 16:19
  • Well what did you try exactly? Help us help you. Do as much of the work yourself as you can, then we can fill in the pieces. It also avoids us repeating something that you've already tried but didn't work. For more tips, see [ask]. Also please take the [tour]. – wjandrea Apr 28 '22 at 16:23
  • I agree, that is what I have done for half a day :). I think i have finally made up some soup that gives me the same result as in PHP (I will post this as answer). I do not fully understand this, but it works. If there are better approaches - i would be glad to know. Python is very nice but I think that when working with dates PHP is far much easier. – octav Apr 28 '22 at 16:38

1 Answers1

0

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()))
octav
  • 3
  • 4