如何让 Python 使用从今天算起两年前的数据创建一个变量

How to Have Python Make a Variable with a Data Two Years Ago from Todays Date

所以我需要在 python 中创建一个变量,让它发送两年前的今天日​​期。我必须使用 Selenium 在 Salesforce 中自动生成一份报告,并且需要通过变量的 send.keys() 方法创建表单。

我今天日期的变量是:

from datetime import date
import time
today = date.today()
current_date = today.strftime("%m/%d/%Y")

但是,我需要过去的日期是两年前打印的那个值。

from datetime import date
import time
today = date.today()
past_date = today.strftime("%m/%d/%Y") - 2*(365)

但是,我得到了这个输出:

>>> past_date = today.strftime("%m/%d/%Y") - 2*(365)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'int'

我认为它与整数运算和字符串运算在同一个变量中有关,从而导致字符串不匹配。有没有人有解决方案可以帮助我以动态方式获取两年前的日期?

非常感谢@EυìγγελοςΓρηγορόπουλος 我能够根据他在 How to subtract a day from a date?

中的评论进行以下工作

我能够使用

from datetime import datetime, timedelta
past_date = datetime.today() - timedelta(days=730)

这些都可以用标准库来完成。

为了具体解决您的错误,您在这一行中将日期转换为字符串,然后尝试从中减去数字。

past_date = today.strftime("%m/%d/%Y") - 2*(365)

不过,为了解决您的问题,我们可以稍微修改一下代码:

from datetime import date
today = date.today()
current_date = today.strftime("%m/%d/%Y")

try:
    past_date = today.replace(year=today.year-2) # the 2 on this line is how many years in the past you need.
except ValueError:
    past_date = today.replace(year=today.year-2, day=today.day-1)

print(past_date)

try-except 用于处理闰年问题。