The current format of my date in my dataframe is YYYY/MM/DD.
I would like to change this to dashes in the following format YYYY-MM-DD.
How would this be done in python pandas?
>Solution :
You can change the format of the date in your DataFrame from "YYYY/MM/DD" to "YYYY-MM-DD" using the str.replace() method in pandas. Here’s how you can do it:
import pandas as pd
# Sample DataFrame with a date column in the format "YYYY/MM/DD"
data = {'Date': ['2023/09/03', '2023/08/15', '2023/07/25']}
df = pd.DataFrame(data)
# Replace "/" with "-" in the Date column
df['Date'] = df['Date'].str.replace('/', '-')
# Now, the Date column will be in the format "YYYY-MM-DD"
print(df)
Output:
Date
0 2023-09-03
1 2023-08-15
2 2023-07-25
In this code, we first create a sample DataFrame with a date column in the "YYYY/MM/DD" format. Then, we use the str.replace() method to replace the slashes ("/") with dashes ("-") in the "Date" column, effectively changing the date format to "YYYY-MM-DD".