python - 如何让 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'
我认为它与整数运算和字符串运算在同一个变量中有关,从而导致字符串不匹配。有没有人有解决方案可以帮助我以动态方式获取两年前的日期?
解决方案
这一切都可以通过标准库来完成。
为了专门解决您的错误,在这一行中,您将日期转换为字符串,然后尝试从中减去数字。
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 用于处理闰年问题。
推荐阅读
- python - setup.py 要求 pkg 不存在或存在于特定版本中
- mysql - 如何从sql中的子查询中选择一列?
- svg - threejs:试图将 objloader 传递给 var
- node.js - 使用实体模式的 TypeORM 一对多关系
- python - Python:如何使用变量作为键查询字典
- python - Python Pandas - 基于条件(年/年级)的预录取决策代码规则
- azure-devops - 如何在 azure devops 中自动分配测试套件的多个用户子集,而不是在回归测试中手动选择每个测试人员
- python - Python base64 哈希,输出与 C# 脚本相同
- tooltip - Antd v3 在 Tooltip 上更改插入符号颜色
- python - 如何使用 python 在 Windows 上隐藏 os.system 输出