1

I have been to trying to convert dataframe object to datetime with format Y-m-d. My data looks like:

pdi.head()

     Date                           Predicted_Linear_Regression
0   [2005-02-16T00:00:00.000000000] 0.000663
1   [1982-02-03T00:00:00.000000000] 0.000666
2   [1995-07-12T00:00:00.000000000] 0.000665
3   [1995-03-13T00:00:00.000000000] 0.000666
4   [2009-05-20T00:00:00.000000000] 0.000658

I have tried to convert Date column to str and then tried to convert to datetime but not able. Tried to convert it directly but unable to.

4
  • 1
    Are items in Date lists? Commented Jun 6, 2019 at 18:12
  • is than an array with a single DT? Commented Jun 6, 2019 at 18:12
  • It seems so its a list but when I do pdi['Date'].dtype it gives me dtype('O') Commented Jun 6, 2019 at 18:16
  • 1
    That's because lists are of "object" type to pandas. Commented Jun 6, 2019 at 18:19

2 Answers 2

1

Your Date column contains lists of dates, not dates. Extract the first element of each list, then convert to datetime:

pd.to_datetime(df['Date'].str[0])
Sign up to request clarification or add additional context in comments.

1 Comment

It works if Date is list. If the Date has type string, then str[0] gives you something else.
0

If your df.Date is of type list, then try:

df.Date = pd.to_datetime(np.array(list(df.Date)).flatten())

If it's of type str, try:

df.Date = pd.to_datetime(df.Date.str.slice(1,-1))

And if lazy:

try:
    df.Date = pd.to_datetime(df.Date.str.slice(1,-1))
except:
    df.Date = pd.to_datetime(np.array(list(df.Date)).flatten())

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.