Robin Kohrs
Robin Kohrs

Reputation: 697

Get date from list with `numpy.datetime64`-objects

I have a list with quite some dates. Unfortunately they are all appear as numpy.datetime64-object. Does anyone has an idea of how I could extract the actual date? The list looks like this:

[numpy.datetime64('2016-01-04T00:00:00.000000000'),
 numpy.datetime64('2016-01-14T00:00:00.000000000'),
 numpy.datetime64('2016-01-17T00:00:00.000000000'),
 numpy.datetime64('2016-01-24T00:00:00.000000000'),
...

Upvotes: 0

Views: 3699

Answers (2)

hpaulj
hpaulj

Reputation: 231665

In [570]: alist=[numpy.datetime64('2016-01-04T00:00:00.000000000'), 
     ...:  numpy.datetime64('2016-01-14T00:00:00.000000000'), 
     ...:  numpy.datetime64('2016-01-17T00:00:00.000000000'), 
     ...:  numpy.datetime64('2016-01-24T00:00:00.000000000')]                                             

The list converted into a numpy array:

In [571]: np.hstack(alist)                                                                                
Out[571]: 
array(['2016-01-04T00:00:00.000000000', '2016-01-14T00:00:00.000000000',
       '2016-01-17T00:00:00.000000000', '2016-01-24T00:00:00.000000000'],
      dtype='datetime64[ns]')

date only dtype:

In [572]: np.hstack(alist).astype('datetime64[D]')                                                        
Out[572]: 
array(['2016-01-04', '2016-01-14', '2016-01-17', '2016-01-24'],
      dtype='datetime64[D]')

print string of the whole array:

In [573]: str(np.hstack(alist).astype('datetime64[D]'))                                                   
Out[573]: "['2016-01-04' '2016-01-14' '2016-01-17' '2016-01-24']"

list of print strings:

In [574]: [str(d) for d in np.hstack(alist).astype('datetime64[D]')]                                      
Out[574]: ['2016-01-04', '2016-01-14', '2016-01-17', '2016-01-24']

date strings without conversion:

In [575]: [str(d) for d in alist]                                                                         
Out[575]: 
['2016-01-04T00:00:00.000000000',
 '2016-01-14T00:00:00.000000000',
 '2016-01-17T00:00:00.000000000',
 '2016-01-24T00:00:00.000000000']

Upvotes: 0

YOLO
YOLO

Reputation: 21749

Here's a way to do using .astype:

dates = [str(x.astype('datetime64[D]')) for x in dates_list]

['2016-01-04', '2016-01-14', '2016-01-17', '2016-01-24']

Upvotes: 2

Related Questions