python 读取yyyy-mm-dd 日期
问题解决
在对“上证指数”数据进行处理的过程中,遇到了利用 numpy
读取YYYY-MM-DD
格式的问题。
对于%m%d%Y
格式的日期,可利用matplotlib.dates.strpdate2num('%m%d%Y')
进行处理。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
date,open,close=np.loadtxt('000001.csv',delimiter=',',converters={0:mdates.strpdate2num('%m%d%Y')},skiprows=1,usecols=(0,3,6),unpack=True)
对于%Y-%m-%d
格式的日期,需要事先创建一个映射函数,将时间转换为浮点数,并在np.loadtxt()
中的 converters
中进行使用。
import numpy as np
import matplotlib.pyplot as plt
import datetime
import time
#def convert_to_tic(s):
# return time.mktime(datetime.datetime.strptime(s.decode('ascii'), "%Y-%m-%d").timetuple())
def datestring2num(s):
return mdates.datestr2num(s.decode('ascii'))
date, close, open = np.loadtxt('000001.csv', delimiter=',', converters={0: datestring2num}, skiprows=1, usecols=(0, 3, 6), unpack=True) # 将日期进行转化
plt.plot(date, open)
plt.show()
报错分析
- 在使用
datetime.datetime.strptime(s, "%Y-%m-%d")
,若s
后不进行解码操作,在调用过程中会出现如下报错:
源码如下:
def convert_to_tic(s):
return time.mktime(datetime.datetime.strptime(s, "%Y-%m-%d").timetuple())
dates=np.loadtxt('data.csv', delimiter=',', usecols=(0,), converters={1: convert_to_tic}, unpack=True)
报错:
TypeError: strptime() argument 1 must be str, not bytes
- 源码如下:
def datestring2num(s):
return mdates.datestr2num(s)
dates=np.loadtxt('data.csv', delimiter=',', usecols=(0,), converters={1: datestring2num}, unpack=True)
报错:
AttributeError: 'numpy.ndarray' object has no attribute 'toordinal'
这是因为我们是以二进制编码的格式打开第一列值,返回的值字节字符串bytes,所以需要把它编译回string,则对字符串解码用函数decode('ascii')
,变成string格式。
参考链接
[1] 关于TypeError: strptime() argument 1 must be str, not bytes解析
[2] Numpy 常用函数及读写操作
[3] Convert date column in dataframe to ticks in python
[5] python docs - [datetime
](https://docs.python.org/3/library/datetime.html?highlight=time strptime#module-datetime) — Basic date and time types