Lance Dacey Lance Dacey - 7 months ago 12
Python Question

date_range not accepting the variable I want to use?

When I input a value like '2015-08', my date_range works as intended. If I use the startdate variable, then it no longer works? I cannot figure out why this would be.

The error I get is "Cannot convert input to Timestamp"

Answer

Not for points. I'm a bit confused, isn't what you're doing just basically the following?

Code:

from datetime import datetime, timedelta

now = datetime.now()
print now.strftime("%Y-%m")
month_ago = now.replace(day=1) - timedelta(days = 1)
print month_ago.strftime("%Y-%m")
months_ago = month_ago.replace(day=1) - timedelta(days = 1)
print months_ago.strftime("%Y-%m")

Output:

2015-11
2015-10
2015-09

The above might not be the perfect answer, but you can substitute any datetime for now and it will give you basically the current and last two months. Adjust as needed, of course.

EDIT:

You can even take it a step further and just create a function that allows you to specify the numbers of months back or use a custom date.

from datetime import datetime, timedelta

def last_n_months(num_of_months, start_date=datetime.now(), include_curr=True):
    f = "%Y-%m"
    curr = start_date
    if include_curr:
        yield curr.strftime(f)
    for num in range(num_of_months):
        curr = curr.replace(day=1) - timedelta(days=1)
        yield curr.strftime(f)

# This month and last 12 months.
print [m for m in last_n_months(12)]
# ['2015-11', '2015-10', '2015-09', '2015-08', '2015-07', '2015-06', '2015-05', '2015-04', '2015-03', '2015-02', '2015-01', '2014-12', '2014-11']

# Last 12 months only.
print [m for m in last_n_months(12, include_curr=False)]
# ['2015-10', '2015-09', '2015-08', '2015-07', '2015-06', '2015-05', '2015-04', '2015-03', '2015-02', '2015-01', '2014-12', '2014-11']    

# Last 12 months from custom date, exclude custom date.
d = datetime(2012, 6, 1)
print [m for m in last_n_months(12, d, False)]
# ['2012-05', '2012-04', '2012-03', '2012-02', '2012-01', '2011-12', '2011-11', '2011-10', '2011-09', '2011-08', '2011-07', '2011-06']