2017-03-07 68 views
0

我想創建一個應用程序,它使用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: time data ' 2017-03-06' does not match format '%Y-%m-%d'

回答

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