1

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.

4
  • 1
    Does .22 mean 2022 or 1922? Commented Aug 17, 2022 at 3:02
  • @TimBiegeleisen 2022 Commented Aug 17, 2022 at 3:03
  • If you want to keep it as an array, you need to convert it to a valid dtype. Commented Aug 17, 2022 at 3:03
  • Can you provide the expected output? Do you want strings/numbers? Commented Aug 17, 2022 at 4:22

1 Answer 1

2

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])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.