2012-03-06 134 views
1

我必須編寫一個程序,從雅虎財經獲取股票並打印出該網站的某些信息。其中一條數據是日期。我需要採取日期如3/21/2012和轉換器到以下格式:2012年3月21日。Python日期字符串mm/dd/yyyy到日期時間

這是我的整個項目的代碼。

def getStockData(company="GOOG"): 

    baseurl ="http://quote.yahoo.com/d/quotes.csv?s={0}&f=sl1d1t1c1ohgvj1pp2owern&e=.csv" 

    url = baseurl.format(company) 
    conn = u.urlopen(url) 
    content = conn.readlines() 
    data = content[0].decode("utf-8") 
    data = data.split(",") 
    date = data[2][1:-1] 
    date_new = datetime.strptime(date, "%m/%d/%Y").strftime("%B[0:3] %d, %Y") 
    print("The last trade for",company, "was", data[1],"and the change was", data[4],"on", date_new) 


company = input("What company would you like to look up?") 
getStockData(company) 


co = ["VOD.L", "AAPL", "YHOO", "S", "T"] 
for company in co: 
    getStockData(company) 

回答

2

你真的應該指定你的代碼時不工作(即,你得到什麼輸出你別指望什麼錯誤信息你好嗎,如果有的話?)。不過,我懷疑你的問題是這個部分:

strftime('%B[0:3] %d, %Y') 

因爲Python不會做你認爲與企圖切片'%B'。您應改爲使用'%b',其中as noted in the documentation for strftime()對應於區域設置縮寫的月份名稱。


編輯

這是基於你發佈什麼上面有我的建議的修改功能齊全的腳本:

import urllib2 as u 
from datetime import datetime 

def getStockData(company="GOOG"): 
    baseurl ="http://quote.yahoo.com/d/quotes.csv?s={0}&f=sl1d1t1c1ohgvj1pp2owern&e=.csv" 

    url = baseurl.format(company) 
    conn = u.urlopen(url) 
    content = conn.readlines() 
    data = content[0].decode("utf-8") 
    data = data.split(",") 
    date = data[2][1:-1] 
    date_new = datetime.strptime(date, "%m/%d/%Y").strftime("%b %d, %Y") 
    print("The last trade for",company, "was", data[1],"and the change was", data[4],"on", date_new) 

for company in ["VOD.L", "AAPL", "YHOO", "S", "T"]: 
    getStockData(company) 

這個腳本的輸出是:

The last trade for VOD.L was 170.00 and the change was -1.05 on Mar 06, 2012 
The last trade for AAPL was 530.26 and the change was -2.90 on Mar 06, 2012 
The last trade for YHOO was 14.415 and the change was -0.205 on Mar 06, 2012 
The last trade for S was 2.39 and the change was -0.04 on Mar 06, 2012 
The last trade for T was 30.725 and the change was -0.265 on Mar 06, 2012 

爲了什麼是值得的,我正在運行這個Python 2.7.1。我也有行from __future__ import print_function使這與您似乎正在使用的Python3打印功能兼容。

+0

這是我得到的錯誤: 「回溯(最近通話最後一個): 文件 」F:\ I211 \ a4.py「,第44行,在 getStockData(公司) 文件」 F :\ I211 \ a4.py「,第39行,在getStockData date_new = datetime.strptime(date,」%m /%d /%Y「)。strftime(」%B [0:3]%d,%Y 「) AttributeError:'模塊'對象沒有屬性'strptime'」 – user1251230 2012-03-06 18:26:43

+0

@ user1251230:這聽起來像你在你的文件中有一個類似'import datetime'的行。將其更改爲'from datetime import datetime',它將'datetime'類導入爲'datetime'而不是datetime模塊。 – ig0774 2012-03-06 22:11:37

-1

結賬 Dateutil。您可以使用它將一個字符串解析爲python datetime對象,然後使用strftime打印該對象。

我已經得出結論,自動檢測日期時間值並不總是一個好主意。使用strptime會更好,並指定您想要的格式。