pandas “datetime.date”和“str”的实例之间不支持“<”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49554491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
'<' not supported between instances of 'datetime.date' and 'str'
提问by Xiaowu Zhao
I get a TypeError:
我得到一个类型错误:
TypeError: '<' not supported between instances of 'datetime.date' and 'str'`
While running the following piece of code:
在运行以下代码时:
import requests
import re
import json
import pandas as pd
def retrieve_quotes_historical(stock_code):
quotes = []
url = 'https://finance.yahoo.com/quote/%s/history?p=%s' % (stock_code, stock_code)
r = requests.get(url)
m = re.findall('"HistoricalPriceStore":{"prices":(.*?),"isPending"',
r.text)
if m:
quotes = json.loads(m[0])
quotes = quotes[::-1]
return [item for item in quotes if not 'type' in item]
quotes = retrieve_quotes_historical('INTC')
df=pd.DataFrame(quotes)
s=pd.Series(pd.to_datetime(df.date,unit='s'))
df.date=s.dt.date
df=df.set_index('date')
This piece runs all smooth, but when I try to run this piece of code:
这段运行很顺利,但是当我尝试运行这段代码时:
df['2017-07-07':'2017-07-10']
I get the TypeError.
我得到了类型错误。
Can anyone help me?
谁能帮我?
回答by Paul
The thing is you want to slice using Strings '2017-07-07'
while your index is of type datetime.date. Your slices should be of this type too.
问题是你想使用字符串切片,'2017-07-07'
而你的索引是 datetime.date 类型。你的切片也应该是这种类型。
You can do this by defining your startdate and endate as follows:
您可以通过如下定义开始日期和结束日期来完成此操作:
import pandas as pd
startdate = pd.to_datetime("2017-7-7").date()
enddate = pd.to_datetime("2017-7-10").date()
df.loc[startdate:enddate]
startdate & enddate are now of type datetime.date and your slice will work:
startdate 和 enddate 现在是 datetime.date 类型,您的切片将起作用:
adjclose close high low open volume
date
2017-07-07 33.205006 33.880001 34.119999 33.700001 33.700001 18304500
2017-07-10 32.979588 33.650002 33.740002 33.230000 33.250000 29918400
It is also possible to create datetime.date type without pandas:
也可以在没有 Pandas 的情况下创建 datetime.date 类型:
import datetime
startdate = datetime.datetime.strptime('2017-07-07', "%Y-%m-%d").date()
enddate = datetime.datetime.strptime('2017-07-10', "%Y-%m-%d").date()