getintoityuh
getintoityuh

Reputation: 41

Convert Strings in Array to Datetime '%Y'

I have a python array:

import numpy as np
import datetime

ray = ['01.01.88', '01.01.99', '01.01.87', '01.01.89', '01.01.96',
       '01.01.95', '01.01.95']

ray = np.array(ray)
type(ray)
ray

I'd like to convert the strings in this array to an array of dates in the %Y format. If possible, please do not convert ray back to a list, I need to keep it as an array.

Upvotes: 1

Views: 288

Answers (1)

mozway
mozway

Reputation: 260620

If you want a vectorial transformation, I would suggest to use pandas's to_datetime:

import pandas as pd
ray = pd.to_datetime(ray).values

Output:

array(['1988-01-01T00:00:00.000000000', '1999-01-01T00:00:00.000000000',
       '1987-01-01T00:00:00.000000000', '1989-01-01T00:00:00.000000000',
       '1996-01-01T00:00:00.000000000', '1995-01-01T00:00:00.000000000',
       '1995-01-01T00:00:00.000000000'], dtype='datetime64[ns]')

Notes. I'm assuming a MM.DD.YY format, if DD.MM.YY use dayfirst=True as parameter of to_datetime. Also, using values and not to_numpy() on purpose to avoid the unnecessary copy of the underlying array.

To have the years as strings:

out = pd.to_datetime(ray).strftime('%Y').values

Output:

array(['1988', '1999', '1987', '1989', '1996', '1995', '1995'],
      dtype=object)

As integers:

out = pd.to_datetime(ray).year.values

Output:

array([1988, 1999, 1987, 1989, 1996, 1995, 1995])

Upvotes: 2

Related Questions