Python string for datetime, find yesterday, then go back to string

I am trying to do the following:

  • read date from file (date format is% Y-% m-% d)
  • convert string to datetime obj (I do this with strptime)
  • get day before in datetime
  • convert the previous day (look_back) back to the string with the specified format

Steps 1 and 2 are not the problem that I am doing 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 that I tried to get the date before the date of dating (No. 3 above) throws an error. My code is:

 look_back = look_back-timedelta(days=1) 

Error:

 look_back = look_back-timedelta(days=1) TypeError: unsupported operand type(s) for -: 'time.struct_time' and 'datetime.timedelta' 

Any ideas on how to do this?

+4
source share
1 answer

datetime.datetime objects have the strptime() method:

 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') 
+3
source

Source: https://habr.com/ru/post/1502665/


All Articles