简体   繁体   English

如何根据从今天开始的过去日期在 Python 中查找下一天

[英]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 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.我需要一个 python 脚本来获取从今天开始的下一个日期(+1 周),以便与过去的日期在同一工作日。

for example: for 2022-03-28 I need to get 2022-05-09例如:对于 2022-03-28 我需要得到 2022-05-09

In PHP I do like this:在 PHP 中,我是这样的:

<?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.实际上我只需要将这个 PHP 代码翻译成 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).我不知道它是否正确,但是这个似乎给我的结果与 PHP 中的结果相同(没有增加 1 周,但对我的目的来说没问题)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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