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?
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?
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".
You don't have to use replace
it. Use format
to format your date
column. This is more pythonic way of doing it. For millions of rows data, replace
method is extremely inefficient.
# Create a list of data
data = ["2023/03/19", "2023/04/16", "2023/06/21", "2023/09/21", "2023/12/31"]
# Create a pandas DataFrame
df = pd.DataFrame(data, columns=["date"])
df['date'] = pd.to_datetime(df['date'], format = "%Y/%m/%d")
# Print the DataFrame
print(df)
date
0 2023-03-19
1 2023-04-16
2 2023-06-21
3 2023-09-21
4 2023-12-31