首页 > 解决方案 > 如何让 Python 用两年前从今天开始的数据创建变量

问题描述

所以我需要在 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'

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

标签: pythondatetimepython-datetimepython-dateutil

解决方案


这一切都可以通过标准库来完成。

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

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 用于处理闰年问题。


推荐阅读