Python-dataframe - pandas - How to add - to the cell that has dates

Category: python pandas datetime (4 Views)

I have a 'date' column that has a date value as 20170423 (yyyymmdd) how can i change it to 2017-04-23?

dataframe = df column name 'date'

I read the below post, but none of the solutions worked

Fastest way to insert these dashes in python string?

Example

d = df['Date'] 
df['Date'] = '%s-%s-%s' % (d[:4], d[4:6], d[6:])

The output 0 0 20170711\n1 20170718\n2 20170718\n3... when i exported in .csv

🔴 No definitive solution yet

📌 Solution 1

Use pd.to_datetime with the specific format of your date.

df['Date'] = pd.to_datetime(df['Date'], format='%Y%m%d')
print(df)

Output:

        Date
0 2017-07-11
1 2017-07-18
2 2017-04-23

Input DataFrame:

       Date
0  20170711
1  20170718
2  20170423