使用numpy读取自定义格式的日期时间 [英] Read a custom formatted datetime with numpy
问题描述
我正在尝试从某些文件中加载时间序列数据.数据具有这种格式
I'm trying to load time series data from some files. The data has this format
04/02/2015 19:07:53.951,3195,1751,-44,-25
我正在使用此代码将整个文件作为numpy对象加载.
I'm using this code to load the whole file as a numpy object.
content = np.loadtxt(filename, dtype={'names': ('timestamp', 'tick', 'ch', 'NodeI', 'Base'),
'formats': ('datetime64[us]', 'i4', 'i4', 'i4', 'i4')}, delimiter=',', skiprows=27)
但是日期时间格式出现错误
but i got an error with the datetime format
ValueError: Error parsing datetime string "04/02/2015 19:07:53.951" at position 2
有一种简单的方法可以定义我正在读取的日期时间格式吗?有大量数据的文件,所以我尝试不超过一次地遍历文件.
there is an easy way to define the datetime format I'm reading? There files with a lot of data so I'm trying not to walk the file more than once.
推荐答案
使用converters
参数以便将转换器函数应用于第一列上的数据:
Use the converters
argument in order to apply a converter function to the data on the first column:
import datetime
def parsetime(v):
return np.datetime64(
datetime.datetime.strptime(v, '%d/%m/%Y %H:%M:%S.%f')
)
content = np.loadtxt(
filename,
dtype={
'names': ('timestamp', 'tick', 'ch', 'NodeI', 'Base'),
'formats': ('datetime64[us]', 'i4', 'i4', 'i4', 'i4')
},
delimiter=',',
skiprows=27,
converters={0: parsetime},
)
我假设您的数据文件使用的是D/M/Y
,如果使用的是M/D/Y
,请相应地调整格式字符串.
I assume your data file is using D/M/Y
, adjust the format string accordingly if you are using M/D/Y
.
这篇关于使用numpy读取自定义格式的日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!