-1

I have data, which I've formatted and sliced in the following format:

currentTime = datetime.now().strftime("%m-%d-%Y")

which returns dates such as this:

09-20-2017

I want to compare this date, or rather the timedelta of this date some time period back, let's say 7 days, so it would be:

09-13-2017

Now, my code says the following:

if currentTime.timedelta(days=7) < furtherSplit[0:10]:

Which ideally I'd like to activate when the currentTime, of timedelta 7, was an earlier date than the furtherSplit[0:10], which is another date, formatted in the same way, but cut from some segment of text, which has the date and another string. If I were to print furtherSplit[0:10], it returns a date like this:

09-18-2017

How would I get this to work? I have made sure timedelta was imported, and printed the individual dates to see they were working. However, when I do currentTime.timedelta(days=7), it does not print.

EDIT

On the help / request of Brad Solomon, here is an updated issue:

So, in using:

from dateutil.relativedelta import relativedelta
...
def compare_dates(date1, date2, **kwargs):
    date1 = datetime.datetime.strptime(date1, '%m-%d-%Y')
    date2 = datetime.datetime.strptime(date2, '%m-%d-%Y')
    td = relativedelta(**kwargs)
    return date1 - td < date2
...
if compare_dates(currentTime, furtherSplit[0:10], days=7):
                    someList.append(x)
                    print ("get here")

It never prints or appends the 'x' to someList. Everything being used is valid. Please advise!

Sam G
  • 3
  • 5

1 Answers1

2

Use relativedelta from the dateutil module.

from datetime import datetime
from dateutil.relativedelta import relativedelta

def compare_dates(date1, date2, **kwargs):
    date1 = datetime.strptime(date1, '%m-%d-%Y')
    date2 = datetime.strptime(date2, '%m-%d-%Y')
    td = relativedelta(**kwargs)
    return date1 - td < date2

d1 = datetime.now().strftime('%m-%d-%Y')
d2 = '09-18-2017'

print(compare_dates(d1, d2, days=7))
True

Tying back to your specific example: the function says, compare (date1 minus some timedelta) to (date2). In your example, date1 is today and date1 is Sep 18. The function takes string-form dates rather than datetime objects as inputs.

I used **kwargs to let you pass any keyword argument that you want to relativedelta. For instance, you could also specify weeks=2.

Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
  • `09-13-2017` is what the string of `furtherSplit[0:10]` is. It comes from a line directly above it which has `someContent.split('\n----\n')[3]` which I know is valid because the date I started this comment with is printed immediately after for testing purposes. I'll try restarting. – Sam G Sep 20 '17 at 15:52