Python Numpy Loadtxt - 转换 unix 时间戳 [英] Python Numpy Loadtxt - Convert unix timestamp

查看:71
本文介绍了Python Numpy Loadtxt - 转换 unix 时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含许多行数据的文本文件-每行中的第一条数据是unix时间戳,例如 1436472000 .我正在使用 numpy.loadtxt ,并且在转换器的参数中,我想为其指定以将时间戳转换为numpy理解为日期时间的任何内容.我知道这需要放在大括号中的 0:之后,但是我不知道如何进行转换.我知道转换器可以从 matplotlib.dates.strpdate2num 用于正常日期,但我这不适用于 unix 时间戳.

I have a text file with many rows of data - the first piece of data in each row is a unix timestamp such as 1436472000. I am using numpy.loadtxt and in the parameters for converters I want to specify for it to convert the timestamp into whatever numpy understands as a date time. I know this needs to go after the 0: in the curly brackets, but I can't work out how to convert it. I know a converter can be used from matplotlib.dates.strpdate2num for normal dates, but I this won't work for unix timestamps.

代码:

timestamp, closep, highp, lowp, openp, volume = np.loadtxt(fileName,delimiter=",",unpack=True,converters={ 0: })

在此先感谢您的帮助,请询问您是否希望我阐明我的意思.

Thanks for help in advance, please ask if you would like me to clarify what I mean.

推荐答案

虽然转换器很方便,但它们很慢,因为它们对每一行数据都调用一次.将时间戳加载到整数的NumPy数组中后,转换数据的速度更快:

While converters can be convenient, they are slow because they are called once for each row of data. It is faster to convert the data after the timestamps are loaded into a NumPy array of integers:

x = np.array([1436472000, 1436472001])
x = np.asarray(x, dtype='datetime64[s]')

产生一组 NumPy datetime64:

array(['2015-07-09T16:00:00-0400', '2015-07-09T16:00:01-0400'],
       dtype='datetime64[s]')

要获取Python datetime.datetime ,请使用 tolist():

To obtain Python datetime.datetimes use tolist():

>>> x.tolist()
# [datetime.datetime(2015, 7, 9, 20, 0), 
#  datetime.datetime(2015, 7, 9, 20, 0, 1)]

<小时>

如您所知,matplotlib datenums 计算自 0001-01-01 以来的 天数00:00:00 UTC,加一.这些不是时间戳(从纪元,1970-01-01 00:00:00 UTC):


As you know, matplotlib datenums count the number of days since 0001-01-01 00:00:00 UTC, plus one. These are not timestamps (which count seconds since the Epoch, 1970-01-01 00:00:00 UTC):

>>> matplotlib.dates.date2num(x.tolist())
# array([ 735788.83333333,  735788.83334491])

这篇关于Python Numpy Loadtxt - 转换 unix 时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆