Numpy.loadtxt unix timestamp converter

I have a large file consisting of OHLC values ​​and stocks. Each line starts with a unix timestamp. How can I convert it to a datetime object that numpy will understand. Here is my code:

entry_timestamp, entry_close, entry_high, entry_low, entry_open, entry_volume = \
    np.loadtxt(filename, delimiter = ',', unpack = True,
               converters = { 0 : lambda data: datetime.datetime.fromtimestamp(float(data))})

And here is an example of a string of data that I am trying to load into arrays:

1441197159,75.54,100

1441197159 is a unix timestamp. I know how to manually convert it to a datetime object, but how to pass it to np.loadtxt as a converter? Thanks

+4
source share
1 answer

, . , dtype , float64. , datetime s, float.

loadtxt, dtype:

import numpy as np
from datetime.datetime import fromtimestamp

filename = 'tmp.txt'

entry_timestamp, entry_close, entry_high, entry_low, entry_open, entry_volume = \
    np.loadtxt(filename, dtype='O,'+'f8,'*5, delimiter=',', unpack=True,
               converters={0: lambda d: fromtimestamp(float(d))})

'O' np.dtype('O') dtype=object. 'f8', , np.dtype('float64'). dtype 6 :

>>> np.dtype('O,'+'f8,'*5)
dtype([('f0', 'O'), ('f1', '<f8'), ('f2', '<f8'), ('f3', '<f8'), ('f4', '<f8'), ('f5', '<f8')])

unpack=True, .

+3

Source: https://habr.com/ru/post/1607910/


All Articles