1

I have a csv file with column 'date' which has dates in many different formats like ddmmyy, mmddyy,yymmdd. I want to convert all the dates to y-m-d format

df=pd.read_csv(file)
df=df['date] .dt.strftime(%y-%m-%d)

This code gives error: "Can only use .dt accessor with datetimelike values"

enter image description here

2 Answers 2

5

You can utilise pd.to_datetime -

>>> import pandas as pd
>>> 
>>> df = pd.DataFrame(['1/2/2020','12/31/2020','20-Jun-20'],columns=['Date'])
>>> df
         Date
0    1/2/2020
1  12/31/2020
2   20-Jun-20
>>> 
>>> df['Date'] = pd.to_datetime(df['Date'])
>>> df
        Date
0 2020-01-02
1 2020-12-31
2 2020-06-20
>>> 
>>> df['Date'] = pd.to_datetime(df['Date']).dt.strftime('%y-%m-%d')
>>> 
>>> df
       Date
0  20-01-02
1  20-12-31
2  20-06-20
>>> 


4

Step 0:-

Your dataframe:-

df=pd.read_csv('your file name.csv')

Step 1:-

firstly convert your 'date' column into datetime by using to_datetime() method:-

df['date']=pd.to_datetime(df['date'])

Step 2:-

And If you want to convert them in string like format Then use:-

df['date']=df['date'].astype(str)

Now if you print df or write df(if you are using jupyter notebook)

Output:-

0    2020-01-01
1    2020-12-31
2    2020-06-20
8
  • Thanks. How to sort by date in this case?
    – Ussu20
    Commented Mar 4, 2021 at 5:04
  • Just use df.sort_values(by='date',ascending=True) and if you want to sort in descending order then set ascending=False in sort_values() method.............btw if this answer helped you then try considering accept this answer Commented Mar 4, 2021 at 5:09
  • The output gives 20-01-01. Instead, I want 2020-01-01. It seems dt.strftime(%y-%m-%d) trimes the year part. Is there a way to gives output as 2020-01-01?
    – Ussu20
    Commented Mar 4, 2021 at 5:39
  • Yeah just use df['date']=df['date'].astype(str) it will convert your 'date' column into Object type and you will get 2020-01-01 as output Commented Mar 4, 2021 at 5:42
  • Sorry, where to insert this? I tried inserting it before pd.to_datetime so that it convert date to a string and also at the end. but it gives error: Can only use .dt accessor with datetimelike values
    – Ussu20
    Commented Mar 4, 2021 at 6:19

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.