簡體   English   中英

為什么在運行此腳本時獲取無效的文字?

[英]Why getting invalid literal when running this script?

當我運行以下腳本時,當日期僅包含1位數字(即02-02-2011)時,我得到ValueError:int()的無效文字,基數為10:“ 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()

在所有情況下,您的create_date()函數都不會返回兩位數的日期和月份數字。

嘗試顯式格式化值,而不是使用str()

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM