Subtracting n days from date in Python

Isak picture Isak · Sep 1, 2015 · Viewed 39.4k times · Source

I want to subtract n days from a file's timestamp, but it doesn't seem to be working. I have read this post, and I think I'm close.

This is an excerpt from my code:

import os, time
from datetime import datetime, timedelta

def processData1( pageFile ):
    f = open(pageFile, "r")
    page = f.read()
    filedate = time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime(pageFile)))
    print filedate
    end_date = filedate - datetime.timedelta(days=10)
    print end_date

Printing filedate works, so that date is read correctly from the files. It's the subtraction bit that doesn't seem to be working.

Desired output: If filedate is 06/11/2013, print end_date should yield 06/01/2013.

Answer

taesu picture taesu · Sep 1, 2015

cleaned up import

from datetime import datetime, timedelta
start = '06/11/2013'
start = datetime.strptime(start, "%m/%d/%Y") #string to date
end = start - timedelta(days=10) # date - days
print start,end