0

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?

Alexander
  • 27
  • 5
  • Does this answer your question? [Change datetime format from dash to slash](https://stackoverflow.com/questions/61241121/change-datetime-format-from-dash-to-slash) – Aqib Chattha Sep 02 '23 at 18:16
  • Try referring this https://stackoverflow.com/questions/38067704/how-to-change-the-datetime-format-in-pandas – Omkar Pattanaik Sep 02 '23 at 18:19

2 Answers2

0

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".

MH RONY
  • 24
  • 1
0

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
ragas
  • 848
  • 2
  • 7