Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when comparing two dates

Trying to compare two dates in Python. When I run a type() check, both show up as <type 'datetime.date'>

And yet when I run a simple check against the two dates, I get the following error:

AttributeError: 'datetime.date' object has no attribute 'date'

Can anyone tell me what I'm doing wrong here. Code below:

d_today = date.today()
oldestDate = d_today - BDay(750)
avgArray2 = [x for x in avgArray if x[0] >= oldestDate.date()]

print type(oldestDate.date())
print type(avgArray[0][0])

And the output:

<type 'datetime.date'>
<type 'datetime.date'>
avgArray2 = [x for x in avgArray if x[0].date() >= oldestDate.date()]
AttributeError: 'datetime.date' object has no attribute 'date'

Full code for how the "avgArray" is build:

d_today = date.today()
d_ref = d_today - BDay(66)
lastDateData = dates[0]

avgArray = []

while (d_ref >= lastDateData):
    avg_data = [x for x in stockData_sorted if (x[0] >= d_ref and x[0] <= d_ref + BDay(22))]
    avg_dates = [d[0] for d in avg_data]
    avg_graphData = [d[1] for d in avg_data]

    workingAvg = sum(avg_graphData)/len(avg_graphData)
    avgArray.append((d_today,workingAvg))

    d_today = d_today - BDay(1)
    d_ref = d_ref - BDay(1)
like image 929
JDGD Avatar asked Feb 02 '15 01:02

JDGD


2 Answers

You have a 'pandas.tslib.Timestamp' not a normal datetime object; which does not have a .date() method.

 avgArray2 = [x for x in avgArray
              if datetime.date(x[0].year, x[0].month, x[0].day) >= oldestDate.date()]
like image 104
Burhan Khalid Avatar answered Sep 28 '22 11:09

Burhan Khalid


If you already have two instances of datetime.date, as per your output:

<type 'datetime.date'>
<type 'datetime.date'>

then the error is calling a non-existent date method on each -- they're already dates, just compare them directly.

IOW, in lieu of

if x[0].date() >= oldestDate.date()

just

if x[0] >= oldestDate

should work fine.

Added: it seems that despite the misleading output x[0] is not a datetime.date but rather a pandas timestamp (I'm unable in this case to explain the output). If that's the case,

datetime.date(x[0].year, x[0].month, x[0].day) >= oldestDate

might work better.

like image 30
Alex Martelli Avatar answered Sep 28 '22 13:09

Alex Martelli