Home > other >  Is 'format' an invalid parameter to to_datetime in pandas?
Is 'format' an invalid parameter to to_datetime in pandas?

Time:05-19

I have the following code as below to create a 'Date' column with date values parsed from another column 'Open Time', which contains a both date and time eg 1/1/2022 10:40:00

The code is as follows:

# create date column 
df.insert(3,"Date",pd.to_datetime(df["Open Time"]).dt.date, format='%d/%m/%Y')
df["Date"]=pd.to_datetime(df["Date"])

However, the following error is generated upon running

TypeError                                 Traceback (most recent call last)
C:\Users\JK\AppData\Local\Temp/ipykernel_11644/253220935.py in <module>
      1 # create date column
----> 2 df.insert(3,"Date",pd.to_datetime(df["Open Time"]).dt.date, format='%d/%m/%Y')
      3 df["Date"]=pd.to_datetime(df["Date"])

TypeError: insert() got an unexpected keyword argument 'format'

I found that without the format parameter, the code can run. However, my dates get jumbled up in the output (the dates with days 2nd to 12th are swopped incorrectly with the months). Hence, I really want to fix this error to see if it will resolve the jumbling of day and month issue. Hope can get some advice here. Thanks.

CodePudding user response:

Your format parameter is misplaced. Use:

df.insert(3, "Date", pd.to_datetime(df["Open Time"], format='%d/%m/%Y').dt.date)
  • Related