Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting n days from date in Python [duplicate]

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.

like image 437
Isak Avatar asked Sep 01 '15 14:09

Isak


People also ask

How do I subtract 7 days from a date in Python?

For adding or subtracting Date, we use something called timedelta() function which can be found under the DateTime class. It is used to manipulate Date, and we can perform arithmetic operations on dates like adding or subtracting.

How do you subtract days from a date in Python?

You can subtract a day from a python date using the timedelta object. You need to create a timedelta object with the amount of time you want to subtract. Then subtract it from the date.

How do you subtract days from date objects?

To subtract days to a JavaScript Date object, use the setDate() method. Under that, get the current days and subtract days. JavaScript date setDate() method sets the day of the month for a specified date according to local time.


1 Answers

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 
like image 187
taesu Avatar answered Sep 27 '22 20:09

taesu