将日期从csv文件转换为句子格式
我正在尝试将日期从csv文件转换为句子格式。例如:“2012年8月27日”至2012年8月27日,“2013年1月4日”至2013年1月4日。这是我的代码:将日期从csv文件转换为句子格式,csv,python-3.x,Csv,Python 3.x,我正在尝试将日期从csv文件转换为句子格式。例如:“2012年8月27日”至2012年8月27日,“2013年1月4日”至2013年1月4日。这是我的代码: def getStockData(company): baseurl = 'http://quote.yahoo.com/d/quotes.csv?s=GOOG&f=sl1d1t1c1ohgvj1pp2owern&e=.csv' web_page = urllib.request.urlopen(baseur
def getStockData(company):
baseurl = 'http://quote.yahoo.com/d/quotes.csv?s=GOOG&f=sl1d1t1c1ohgvj1pp2owern&e=.csv'
web_page = urllib.request.urlopen(baseurl)
lines = web_page.read().decode()
web_page.close()
read = csv.reader([lines])
row = next(read)
print('The last trade for', row[0], 'is $'+row[1], ', change rate is '+row[11], 'on '+row[2],'. The open was '+row[5],'and the previous close was '+row[10],'.')
第[2]行表示日期。关于如何实现这一点有什么想法吗?要将
日期的格式从一种文本格式更改为另一种文本格式,最简单的方法是:
- 使用
.strtime()
方法将转换为实际的日期
/日期时间
- 使用
.strftime()
方法将其转换回文本
例如:
from datetime import datetime
close_date = datetime.strptime('%m/%d/%Y')
close_date_text = close_date.strftime('%B %d, %Y')
看到ok,我决定在我的print语句中使用行[2]。strftime(“%B%d%Y”),但是它给了我“TypeError:无法将'list'对象隐式转换为str”,我需要转换为str的列表是什么?@holaprofesor:行[2]
是一个str
(不知道为什么会看到list
),而且strftime
不是str
的一种方法。您需要datetime.date.strtime
来解析str
,然后datetime.data.strftime
将其格式化为新表单。我不知道你是怎么得到这个错误的,因为你给出的代码对这个错误没有意义。所以我需要在print语句中使用strftime之前在一行中使用strptime解析str@ShadowRanger@holaprofesor是的,你知道