Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert numpy array to list of datetimes

I have a 2D array of dates of the form:

[Y Y Y ... ]
[M M M ... ]
[D D D ... ]
[H H H ... ]
[M M M ... ]
[S S S ... ]

So it looks like

data = np.array([
    [2015, 2015, 2015, 2015, 2015, 2015], # ...
    [   1,    1,    1,    1,    1,    1],
    [   1,    1,    1,    2,    2,    2],
    [  23,   23,   23,    0,    0,    0],
    [   4,    5,    5,   37,   37,   37],
    [  59,    1,    2,   25,   27,   29]
])

What would be the best way to convert this into one list of datetime objects?

like image 812
hm8 Avatar asked Oct 20 '16 21:10

hm8


Video Answer


1 Answers

import datetime
import numpy as np

data = np.array(
    [[2015, 2015, 2015, 2015, 2015, 2015],
     [   1,    1,    1,    1,    1,    1],
     [   1,    1,    1,    2,    2,    2],
     [  23,   23,   23,    0,    0,    0],
     [   4,    5,    5,   37,   37,   37],
     [  59,    1,    2,   25,   27,   29]]
)

# Transpose the data so that columns become rows.
data = data.T

# A simple list comprehension does the trick, '*' making sure
# the values are unpacked for 'datetime.datetime'.
new_data = [datetime.datetime(*x) for x in data]

print(new_data)

[datetime.datetime(2015, 1, 1, 23, 4, 59), datetime.datetime(2015, 1, 1, 23, 5, 1), datetime.datetime(2015, 1, 1, 23, 5, 2), datetime.datetime(2015, 1, 2, 0, 37, 25), datetime.datetime(2015, 1, 2, 0, 37, 27), datetime.datetime(2015, 1, 2, 0, 37, 29)]

like image 195
Def_Os Avatar answered Sep 16 '22 13:09

Def_Os