Subtracting n days from date in Python

46,554

Solution 1

When you use time.strftime() you are actually converting a struct_time to a string.

so filedate is actually a string. When you try to + or - a datetime.timedelta from it, you would get an error. Example -

In [5]: s = time.strftime('%m/%d/%Y', time.gmtime(time.time()))

In [6]: s
Out[6]: '09/01/2015'

In [8]: s - datetime.timedelta(days=10)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-fb1d19ed0b02> in <module>()
----> 1 s - datetime.timedelta(days=10)

TypeError: unsupported operand type(s) for -: 'str' and 'datetime.timedelta'

To get a similar behavior to time.gmtime() to can instead use datetime.datetime.utcfromtimestamp() , this would provide a datetime object, from which you can subtract the timedelta.

And then if the end result you want is actually a string, you can use datetime.strftime() to convert it to string in required format. Example -

import os
from datetime import datetime, timedelta

def processData1( pageFile ):
    f = open(pageFile, "r")
    page = f.read()
    filedate = datetime.utcfromtimestamp(os.path.getmtime(pageFile)))
    print filedate
    end_date = filedate - timedelta(days=10)
    print end_date   #end_date would be a datetime object.
    end_date_string = end_date.strftime('%m/%d/%Y')
    print end_date_string

Solution 2

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 
Share:
46,554
Isak
Author by

Isak

Updated on July 30, 2022

Comments

  • Isak
    Isak almost 2 years

    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.

    • Anand S Kumar
      Anand S Kumar over 8 years
      Are you sure you are using time.strftime() ?
    • Isak
      Isak over 8 years
      The code is exactly as in the post, yes, if that's what you mean?
    • Anand S Kumar
      Anand S Kumar over 8 years
      If yiou are getting any error, please add that to the question