我必须编写一个程序,从雅虎财经获取股票并打印该网站的某些信息。其中一项数据是日期。我需要将日期(如 3/21/2012)转换为以下格式:2012 年 3 月 21 日。
这是我整个项目的代码。
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)
最佳答案
您应该真正指定您的代码无法正常工作的原因(即,您得到了哪些您不期望的输出?您收到了什么错误消息(如果有的话)?)。但是,我怀疑您的问题出在这部分:
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 打印函数兼容。
关于Python 日期字符串 mm/dd/yyyy 转日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9577362/