So I need to make a variable in python to have it send off today's date two years ago. I am having to automate a report in Salesforce using Selenium and need to have the form created by a send.keys() method from a variable.
The variable I have for today's date is :
from datetime import date
import time
today = date.today()
current_date = today.strftime("%m/%d/%Y")
However, I need the past date to be that value printed from two years ago.
from datetime import date
import time
today = date.today()
past_date = today.strftime("%m/%d/%Y") - 2*(365)
However, I get this output:
>>> 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'
I presume it has something to with integer operations and string operations being in the same variable, thereby causing a string mismatch. Does anyone have a solution to help me get the date from two years ago in a dynamic way?
This can all be done with standard library.
To specifically address your error, on this line you are turning the date into a string and then trying to subtract numbers from it.
past_date = today.strftime("%m/%d/%Y") - 2*(365)
However to solve your issue we can change the code up a little:
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)
The try-except is to handle leap year issues.