使用 Numpy genfromtext 导入数据并使用日期时间格式化列

Importing data using Numpy genfromtext and formatting column with datetime

我有一个长文本文件,我正在使用 numpy genfromtext 导入:

00:00:01 W 348 18.2 55.9 049 1008.8 0.000 
00:00:02 W 012 12.5 55.9 049 1008.8 0.000 
00:00:03 W 012 12.5 55.9 049 1008.8 0.000
00:00:04 W 357 18.2 55.9 049 1008.8 0.000 
00:00:05 W 357 18.2 55.9 049 1008.8 0.000 
00:00:06 W 339 17.6 55.9 049 1008.8 0.000 

testdata = np.genfromtxt(itertools.islice(f_in, 0, None, 60),\
                         names=('time','ew','d12','s12','t12','p12'.....)

time = (testdata['time'])

这是将所有数据组织成一个数组。文件中的第一列数据是每一行的时间戳。在文本文件中,它的格式为 00:00:00,格式为 (%H:%m:%s)。但是在生成的实际数组中,它会将其变成 1900-01-01 00:00:00 。当我随时间绘制数据时,我无法让它降低 Y-m-d。

我试过了time = time.strftime('%H:%M:%S')dt.datetime.strptime(time.decode('ascii'), '%H:%M:%S')

两者什么都不做。我怎样才能把我的整个时间数组保持原来的 %H:%m:%s 格式而不添加 %Y-%m-%d?

编辑:根据提供的数据,您可以像这样导入文件:

str2date = lambda x: datetime.strptime(x.decode("utf-8"), '%H:%M:%S').time()

data = np.genfromtxt(itertools.islice(f_in, 0, None, 60), dtype=None,names=('time','ew','d12','s12','t12','p12'.....), delimiter=' ', converters = {0: str2date})

print(data['time'])

输出:

00:00:01

请注意,您需要 .decode("utf-8")str2date 输入,因为它接受字节。您可以根据您的具体文件内容在np.genfromtxt()中设置您的dtype

如果您的数据格式正确,您也可以使用此方法:

dt.datetime.strptime(time,"%H:%M:%S").time()