我正在尝试创建一个应用程序,它使用python从网站提取信息,我正在使用datetime
格式。
def constructYFURL(ticker,start_date,end_date,freq):
start_date = datetime.strptime(start_date,"%Y-%m-%d").date()
end_date = datetime.strptime(end_date,"%Y-%m-%d").date()
s=ticker.replace("^","%5E")
if start_date.month-1<10:
a="0"+str(start_date.month-1)
else:
a=str(start_date.month-1)
# Also the month always has 2 digits
b=str(start_date.day)
c=str(start_date.year)
if end_date.month - 1 < 10:
d = "0" + str(end_date.month - 1)
else:
d = str(end_date.month - 1)
e=str(end_date.day)
f=str(end_date.year)
`enter code here`g=freq
yfURL = "http://real-chart.finance.yahoo.com/table.csv? s="+s+"&a="+a+"&b="+b+"&c="+c+"&d="+d+"&e="+e+"&f="+f+"&g="+g+"&ignore=.csv"
return yfURL
from download import constructYFURL
ticker = "AAPL"
start_date = "2016-01-01"
end_date = " 2017-03-06"
freq = "d"
yfURL = constructYFURL(ticker,start_date,end_date,freq)
print yfURL
我收到以下错误消息:
ValueError:时间数据'2017-03-06'与格式'%Y-%m-%d'不匹配
答案 0 :(得分:0)
你有一个额外的领先空间:
end_date = " 2017-03-06"
删除它,你得到的错误消失,程序运行
更好的格式化代码:
def constructYFURL(ticker,start_date,end_date,freq):
start_date = datetime.strptime(start_date,"%Y-%m-%d").date()
end_date = datetime.strptime(end_date,"%Y-%m-%d").date()
s=ticker.replace("^","%5E")
if start_date.month-1<10:
a="0"+str(start_date.month-1)
else:
a=str(start_date.month-1)
# Also the month always has 2 digits
b=str(start_date.day)
c=str(start_date.year)
if end_date.month - 1 < 10:
d = "0" + str(end_date.month - 1)
else:
d = str(end_date.month - 1)
e=str(end_date.day)
f=str(end_date.year)
g=freq
yfURL = "http://real-chart.finance.yahoo.com/table.csv? s="+s+"&a="+a+"&b="+b+"&c="+c+"&d="+d+"&e="+e+"&f="+f+"&g="+g+"&ignore=.csv"
return yfURL
ticker = "AAPL"
start_date = "2016-01-01"
end_date = "2017-03-06"
freq = "d"
yfURL = constructYFURL(ticker,start_date,end_date,freq)
print yfURL