4

Hello I have pandas df as shows above. The date Column has to to be converted.

So I wrote this code:

df2['date']= pd.to_datetime(df2['date'], format = '%Y-%m-%d %H:%M:%S.%f')

And I have this error:

time data test_2021-03-01 02:30:02.237441 doesn't match format specified

i don't know how to proceed Thanks

pandas df

2 Answers 2

2

Try pass errors

df2['date']= pd.to_datetime(df2['date'], format = '%Y-%m-%d %H:%M:%S.%f', errors = 'coerce')

Update split

s = df2['date'].astype(str).str.split('_').str[-1]; 
df2['date'] = pd.to_datetime(s, format = '%Y-%m-%d %H:%M:%S.%f', errors = 'coerce') 
Sign up to request clarification or add additional context in comments.

5 Comments

THANKS So from now, i can split my column ?
@phildrav yes you can df2['date2'] = df2['date'].str.split('_').str[-1]; df2['date']= pd.to_datetime(df2['date2'], format = '%Y-%m-%d %H:%M:%S.%f', errors = 'coerce')
df2['date2'] = df2['date'].str.split('_').str[-1] returns me an error : AttributeError: Can only use .str accessor with string values!
@phildrav adding astype(str)
like this? df2['date2'] = df2['date'].str.split('_').str[-1].astype(str)
0

The error shows that your data has timestamp mixed with some other things. You can try extract it first:

df = pd.DataFrame({'date':['time data test_2021-03-01 02:30:02.237441']})

ext_time = df['date'].str.extract('(\d{4}-\d+-\d+ \d+:\d+:\d+\.\d+)')[0]
df['date'] = pd.to_datetime(ext_time, errors='coerce',  format = '%Y-%m-%d %H:%M:%S.%f'))

Output:

                        date
0 2021-03-01 02:30:02.237441

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.