8

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.

Community
  • 1
  • 1
Isak
  • 495
  • 3
  • 6
  • 15

2 Answers2

17

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 
taesu
  • 4,250
  • 1
  • 19
  • 40
13

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
FatihAkici
  • 3,673
  • 1
  • 20
  • 40
Anand S Kumar
  • 76,986
  • 16
  • 159
  • 156