为什么在运行此脚本时获取无效的文字?

时间:2015-05-13 22:47:36

标签: python dictionary error-handling

当我运行以下脚本时,我得到ValueError:对于基数为10的int()的无效文字:' 2 - '当日期只包含1位数(即02-02-2011)时。但是,当日期有2位数(即11-11-2011)时,它可以正常工作。这是什么原因,我该如何解决?

from __future__ import division
from easygui import *
import ystockquote
import datetime
import math

def main():
    stock = 'NFLX'
    name = ystockquote.get_company_name(stock)
    start_date = create_date(02,13,2009)
    end_date = create_date(10,21,2014)
    start_price = get_price_on_date(stock,start_date)
    end_price = get_price_on_date(stock,end_date)
    if not isinstance(start_price,str):
        print "Please enter a different start date, the market was closed on the day you chose!"
        quit()
    else:
        start_price = float(start_price)
    if not isinstance(end_price,str):
        print "Please enter a different end date, the market was closed on the day you chose!"
        quit()
    else:
        end_price = float(end_price)
    no_of_shares = math.floor(10000/float(start_price))
    profit = (end_price-start_price)*no_of_shares
    print "The profit resulting from investing $10,000 in " + name + " from " + start_date + " to " + end_date + " would have been " + "$" + str(profit) + " or a return of {:.2%}".format(profit/10000) + " ."

def get_price_on_date(stock,date):
    a = ystockquote.get_historical_prices(stock,date,date)
    for key, value in a.iteritems() :
        for key, value in value.iteritems() :
            if key == 'Close':
               return value

def create_date(month,day,year):
    date_string = str(year) + "-" + str(month) + "-" + str(day)
    return date_string

if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:1)

您的create_date()功能在所有情况下均未返回两位数的日期和月份数字。

尝试显式格式化值,而不是使用str()

date_string = "{0:04}-{1:02}-{2:02}".format(year, month, day)