>>> headers
['name', 'price', 'date', 'time', 'change', 'open', 'high', 'low', 'volume']
>>> row
['AA', '39.48', '6/11/2007', '9:36am', '-0.18', '39.67', '39.69', '39.45', '181800']
>>> types = [str, float, str, str, float, float, float, float, int]
>>> converted = [func(val) for func, val in zip(types, row)]
>>> record = dict(zip(headers, converted))
>>> record
{'volume': 181800, 'name': 'AA', 'price': 39.48, 'high': 39.69, 'low': 39.45, 'time': '9:36am', 'date': '6/11/2007', 'open': 39.67, 'change': -0.18}
如何将日期字符串转换为日期元组?
你可以做
def date_to_tuple(datestring):
return tuple(int(part) for part in datestring.split('/'))
并对types
列表中的相关条目使用date_to_tuple
而不是str
。
但您可能希望使用datetime.date
而不是int
s 的元组。例如,日期格式是 MMDDYYYY 还是 DDMMYYYY?字符串或元组无法明确说明这一点。此外,如果您想在某个时候显示日期或计算不同的日期,这将使处理起来容易得多。
data = {'volume': 181800, 'name': 'AA', 'price': 39.48, 'high': 39.69, 'low': 39.45, 'time': '9:36am', 'date': '6/11/2007', 'open': 39.67, 'change': -0.18}
data['date'] = tuple(data['date'].split('/'))