5

I am trying to do the following:

  1. read a date from a file (the format of the date is %Y-%m-%d)
  2. convert a string into a datetime obj (i'm doing this with strptime)
  3. get the day prior to the datetime
  4. convert the day prior (look_back) back into a string with a given format

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?

dbJones
  • 762
  • 1
  • 10
  • 31
  • 2
    Possible duplicate of [How do you convert a python time.struct_time object into a datetime object?](http://stackoverflow.com/questions/1697815/how-do-you-convert-a-python-time-struct-time-object-into-a-datetime-object). You must convert you `time.struct_time` to a `datetime` – Rod Sep 17 '13 at 18:26
  • 1
    @Rod: no, just use `datetime.strptime()` to parse the date instead. – Martijn Pieters Sep 17 '13 at 18:37

1 Answers1

5

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')
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Aaaaah, I was comparing a time object to a datetime object, thereby throwing an error. Makes sense! – dbJones Sep 18 '13 at 18:10