I am trying to do the following:
Steps 1 & 2 are not an issue, which I accomplish like so:
import datetime
from datetime import timedelta
import time
now = datetime.datetime.now() #checks current datetime
### READ LAST RUN DATETIME ###
try:
test = open("last_settings.ini", "r") #opens file in read mode
print "Name of the file: ", test.name
last_run = test.read(10); # just reads the date
print "Program was last run: %s" % last_run
test.close()
firstRun = 'False'
except:
print "Settings file does not exist"
#test = open("last_settings.ini", "w+") #creates the file
#test.close()
#first_run = 'True'
#look_back = str(now-timedelta(days=14)) #sets initial lookBack date of two weeks
#print "Pulling down all paid invoices from date " + look_back
### 24 hour lookback ###
look_back = time.strptime(last_run, "%Y-%m-%d")
However, every method I've tried for getting the date prior to the give date (#3 above) throws an error. My code:
look_back = look_back-timedelta(days=1)
The error:
look_back = look_back-timedelta(days=1)
TypeError: unsupported operand type(s) for -: 'time.struct_time' and 'datetime.timedelta'
Have ideas about how to do this?
Use datetime. date. today() to get today's date in local time. Use today - datetime. timedelta(days=1) to subtract one day from the previous result today .
You just have to subtract no. of days using 'timedelta' that you want to get back in order to get the date from the past. For example, on subtracting two we will get the date of the day before yesterday.
To convert Python datetime to string, use the strftime() function. The strftime() method is a built-in Python method that returns the string representing date and time using date, time, or datetime object.
datetime.datetime
objects have a strptime()
method as well:
read_date = datetime.datetime.strptime(last_run, '%Y-%m-%d')
previous_day = read_date - datetime.timedelta(days=1)
formatted_previous_day = previous_day.strftime('%Y-%m-%d')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With