比较两个日期时出错

时间:2015-02-02 01:52:44

标签: python date datetime

尝试比较Python中的两个日期。当我运行type()检查时,两者都显示为    <type 'datetime.date'>

然而,当我对两个日期进行简单检查时,我收到以下错误:

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

谁能告诉我这里我做错了什么。代码如下:

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])

输出:

<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'

构建“avgArray”的完整代码:

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)

2 个答案:

答案 0 :(得分:4)

你有'pandas.tslib.Timestamp'不是普通的日期时间对象;它没有.date()方法。

 avgArray2 = [x for x in avgArray
              if datetime.date(x[0].year, x[0].month, x[0].day) >= oldestDate.date()]

答案 1 :(得分:1)

如果根据您的输出已经有datetime.date的两个实例:

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

然后错误是在每个方法上调用一个不存在的date方法 - 它们已经是日期,只是直接比较它们。

IOW,代替

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

if x[0] >= oldestDate

应该可以正常工作。

补充:似乎尽管误导性输出x[0] datetime.date而是pandas时间戳(在这种情况下我无法解释输出) 。如果是这样的话,

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

可能会更好。