0

I have a column, 'StartDate' which has 2 types of formats for displaying the dates. The first is '25/12/2022', and the second datetime.datetime(2022, 1, 1, 0, 0). So the first type of value does have the apostrophe and the second doesn't. How can I turn all of these values into the datetime type, formatted as dd/mm/yyyy?

Using the pd.to_datetime() has resulted in NaT values when the input is 'datetime.datetime(2022, 1, 1, 0, 0)', but does result in a datetime type when the input is '25/12/2022', which is something I haven't been able to figure out.

pd.to_datetime results in NaT when I the input is datetime.datetime(2023, 12, 30, 0, 0) and does return a datetime when the input is 01/10/2024. I tried splitting the column into the datetimes and strings, but couldn't get it right.

I checked the amount of unique values in the beginning, which is 611. If I use pd.to_datetime, this is reduced to 509. This results in a lot of issues further down the line. All of the values which aren't parsed are like datetime.datetime(2022, 1, 1, 0, 0).

not_speshal
  • 22,093
  • 2
  • 15
  • 30

1 Answers1

1

In my case I'm not getting Nat as you are suggesting.

import pandas as pd
import datetime as datetime

df = pd.DataFrame({'date': ['25/12/2022', datetime.datetime(2023, 12, 30, 0, 0)]})
df['date'] = pd.to_datetime(df['date'])
print(df)


     date
0 2022-12-25
1 2023-12-30
ragas
  • 848
  • 2
  • 7
  • This code snippet results in a error for me: --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[5], line 4 1 import pandas as pd 2 from datetime import datetime ----> 4 df = pd.DataFrame({'date': ['25/12/2022', datetime.datetime(2023, 12, 30, 0, 0)]}) 5 df['date'] = pd.to_datetime(df['date']) 6 print(df) AttributeError: type object 'datetime.datetime' has no attribute 'datetime' – Robin Keij Aug 02 '23 at 07:38
  • @RobinKeij: I'm not getting this error. Maybe the following link help you resolve the issue. https://stackoverflow.com/questions/12906402/type-object-datetime-datetime-has-no-attribute-datetime – ragas Aug 02 '23 at 10:05